client_auth.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. // Copyright 2015 The etcd Authors
  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 v2http
  15. import (
  16. "encoding/json"
  17. "net/http"
  18. "path"
  19. "strings"
  20. "github.com/coreos/etcd/etcdserver/api"
  21. "github.com/coreos/etcd/etcdserver/api/v2http/httptypes"
  22. "github.com/coreos/etcd/etcdserver/auth"
  23. )
  24. type authHandler struct {
  25. sec auth.Store
  26. cluster api.Cluster
  27. }
  28. func hasWriteRootAccess(sec auth.Store, r *http.Request) bool {
  29. if r.Method == "GET" || r.Method == "HEAD" {
  30. return true
  31. }
  32. return hasRootAccess(sec, r)
  33. }
  34. func hasRootAccess(sec auth.Store, r *http.Request) bool {
  35. if sec == nil {
  36. // No store means no auth available, eg, tests.
  37. return true
  38. }
  39. if !sec.AuthEnabled() {
  40. return true
  41. }
  42. username, password, ok := r.BasicAuth()
  43. if !ok {
  44. return false
  45. }
  46. rootUser, err := sec.GetUser(username)
  47. if err != nil {
  48. return false
  49. }
  50. ok = sec.CheckPassword(rootUser, password)
  51. if !ok {
  52. plog.Warningf("auth: wrong password for user %s", username)
  53. return false
  54. }
  55. for _, role := range rootUser.Roles {
  56. if role == auth.RootRoleName {
  57. return true
  58. }
  59. }
  60. plog.Warningf("auth: user %s does not have the %s role for resource %s.", username, auth.RootRoleName, r.URL.Path)
  61. return false
  62. }
  63. func hasKeyPrefixAccess(sec auth.Store, r *http.Request, key string, recursive bool) bool {
  64. if sec == nil {
  65. // No store means no auth available, eg, tests.
  66. return true
  67. }
  68. if !sec.AuthEnabled() {
  69. return true
  70. }
  71. if r.Header.Get("Authorization") == "" {
  72. plog.Warningf("auth: no authorization provided, checking guest access")
  73. return hasGuestAccess(sec, r, key)
  74. }
  75. username, password, ok := r.BasicAuth()
  76. if !ok {
  77. plog.Warningf("auth: malformed basic auth encoding")
  78. return false
  79. }
  80. user, err := sec.GetUser(username)
  81. if err != nil {
  82. plog.Warningf("auth: no such user: %s.", username)
  83. return false
  84. }
  85. authAsUser := sec.CheckPassword(user, password)
  86. if !authAsUser {
  87. plog.Warningf("auth: incorrect password for user: %s.", username)
  88. return false
  89. }
  90. writeAccess := r.Method != "GET" && r.Method != "HEAD"
  91. for _, roleName := range user.Roles {
  92. role, err := sec.GetRole(roleName)
  93. if err != nil {
  94. continue
  95. }
  96. if recursive {
  97. if role.HasRecursiveAccess(key, writeAccess) {
  98. return true
  99. }
  100. } else if role.HasKeyAccess(key, writeAccess) {
  101. return true
  102. }
  103. }
  104. plog.Warningf("auth: invalid access for user %s on key %s.", username, key)
  105. return false
  106. }
  107. func hasGuestAccess(sec auth.Store, r *http.Request, key string) bool {
  108. writeAccess := r.Method != "GET" && r.Method != "HEAD"
  109. role, err := sec.GetRole(auth.GuestRoleName)
  110. if err != nil {
  111. return false
  112. }
  113. if role.HasKeyAccess(key, writeAccess) {
  114. return true
  115. }
  116. plog.Warningf("auth: invalid access for unauthenticated user on resource %s.", key)
  117. return false
  118. }
  119. func writeNoAuth(w http.ResponseWriter, r *http.Request) {
  120. herr := httptypes.NewHTTPError(http.StatusUnauthorized, "Insufficient credentials")
  121. if err := herr.WriteTo(w); err != nil {
  122. plog.Debugf("error writing HTTPError (%v) to %s", err, r.RemoteAddr)
  123. }
  124. }
  125. func handleAuth(mux *http.ServeMux, sh *authHandler) {
  126. mux.HandleFunc(authPrefix+"/roles", capabilityHandler(authCapability, sh.baseRoles))
  127. mux.HandleFunc(authPrefix+"/roles/", capabilityHandler(authCapability, sh.handleRoles))
  128. mux.HandleFunc(authPrefix+"/users", capabilityHandler(authCapability, sh.baseUsers))
  129. mux.HandleFunc(authPrefix+"/users/", capabilityHandler(authCapability, sh.handleUsers))
  130. mux.HandleFunc(authPrefix+"/enable", capabilityHandler(authCapability, sh.enableDisable))
  131. }
  132. func (sh *authHandler) baseRoles(w http.ResponseWriter, r *http.Request) {
  133. if !allowMethod(w, r.Method, "GET") {
  134. return
  135. }
  136. if !hasRootAccess(sh.sec, r) {
  137. writeNoAuth(w, r)
  138. return
  139. }
  140. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  141. w.Header().Set("Content-Type", "application/json")
  142. roles, err := sh.sec.AllRoles()
  143. if err != nil {
  144. writeError(w, r, err)
  145. return
  146. }
  147. if roles == nil {
  148. roles = make([]string, 0)
  149. }
  150. err = r.ParseForm()
  151. if err != nil {
  152. writeError(w, r, err)
  153. return
  154. }
  155. var rolesCollections struct {
  156. Roles []auth.Role `json:"roles"`
  157. }
  158. for _, roleName := range roles {
  159. var role auth.Role
  160. role, err = sh.sec.GetRole(roleName)
  161. if err != nil {
  162. writeError(w, r, err)
  163. return
  164. }
  165. rolesCollections.Roles = append(rolesCollections.Roles, role)
  166. }
  167. err = json.NewEncoder(w).Encode(rolesCollections)
  168. if err != nil {
  169. plog.Warningf("baseRoles error encoding on %s", r.URL)
  170. writeError(w, r, err)
  171. return
  172. }
  173. }
  174. func (sh *authHandler) handleRoles(w http.ResponseWriter, r *http.Request) {
  175. subpath := path.Clean(r.URL.Path[len(authPrefix):])
  176. // Split "/roles/rolename/command".
  177. // First item is an empty string, second is "roles"
  178. pieces := strings.Split(subpath, "/")
  179. if len(pieces) == 2 {
  180. sh.baseRoles(w, r)
  181. return
  182. }
  183. if len(pieces) != 3 {
  184. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  185. return
  186. }
  187. sh.forRole(w, r, pieces[2])
  188. }
  189. func (sh *authHandler) forRole(w http.ResponseWriter, r *http.Request, role string) {
  190. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  191. return
  192. }
  193. if !hasRootAccess(sh.sec, r) {
  194. writeNoAuth(w, r)
  195. return
  196. }
  197. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  198. w.Header().Set("Content-Type", "application/json")
  199. switch r.Method {
  200. case "GET":
  201. data, err := sh.sec.GetRole(role)
  202. if err != nil {
  203. writeError(w, r, err)
  204. return
  205. }
  206. err = json.NewEncoder(w).Encode(data)
  207. if err != nil {
  208. plog.Warningf("forRole error encoding on %s", r.URL)
  209. return
  210. }
  211. return
  212. case "PUT":
  213. var in auth.Role
  214. err := json.NewDecoder(r.Body).Decode(&in)
  215. if err != nil {
  216. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  217. return
  218. }
  219. if in.Role != role {
  220. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Role JSON name does not match the name in the URL"))
  221. return
  222. }
  223. var out auth.Role
  224. // create
  225. if in.Grant.IsEmpty() && in.Revoke.IsEmpty() {
  226. err = sh.sec.CreateRole(in)
  227. if err != nil {
  228. writeError(w, r, err)
  229. return
  230. }
  231. w.WriteHeader(http.StatusCreated)
  232. out = in
  233. } else {
  234. if !in.Permissions.IsEmpty() {
  235. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Role JSON contains both permissions and grant/revoke"))
  236. return
  237. }
  238. out, err = sh.sec.UpdateRole(in)
  239. if err != nil {
  240. writeError(w, r, err)
  241. return
  242. }
  243. w.WriteHeader(http.StatusOK)
  244. }
  245. err = json.NewEncoder(w).Encode(out)
  246. if err != nil {
  247. plog.Warningf("forRole error encoding on %s", r.URL)
  248. return
  249. }
  250. return
  251. case "DELETE":
  252. err := sh.sec.DeleteRole(role)
  253. if err != nil {
  254. writeError(w, r, err)
  255. return
  256. }
  257. }
  258. }
  259. type userWithRoles struct {
  260. User string `json:"user"`
  261. Roles []auth.Role `json:"roles,omitempty"`
  262. }
  263. type usersCollections struct {
  264. Users []userWithRoles `json:"users"`
  265. }
  266. func (sh *authHandler) baseUsers(w http.ResponseWriter, r *http.Request) {
  267. if !allowMethod(w, r.Method, "GET") {
  268. return
  269. }
  270. if !hasRootAccess(sh.sec, r) {
  271. writeNoAuth(w, r)
  272. return
  273. }
  274. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  275. w.Header().Set("Content-Type", "application/json")
  276. users, err := sh.sec.AllUsers()
  277. if err != nil {
  278. writeError(w, r, err)
  279. return
  280. }
  281. if users == nil {
  282. users = make([]string, 0)
  283. }
  284. err = r.ParseForm()
  285. if err != nil {
  286. writeError(w, r, err)
  287. return
  288. }
  289. ucs := usersCollections{}
  290. for _, userName := range users {
  291. var user auth.User
  292. user, err = sh.sec.GetUser(userName)
  293. if err != nil {
  294. writeError(w, r, err)
  295. return
  296. }
  297. uwr := userWithRoles{User: user.User}
  298. for _, roleName := range user.Roles {
  299. var role auth.Role
  300. role, err = sh.sec.GetRole(roleName)
  301. if err != nil {
  302. continue
  303. }
  304. uwr.Roles = append(uwr.Roles, role)
  305. }
  306. ucs.Users = append(ucs.Users, uwr)
  307. }
  308. err = json.NewEncoder(w).Encode(ucs)
  309. if err != nil {
  310. plog.Warningf("baseUsers error encoding on %s", r.URL)
  311. writeError(w, r, err)
  312. return
  313. }
  314. }
  315. func (sh *authHandler) handleUsers(w http.ResponseWriter, r *http.Request) {
  316. subpath := path.Clean(r.URL.Path[len(authPrefix):])
  317. // Split "/users/username".
  318. // First item is an empty string, second is "users"
  319. pieces := strings.Split(subpath, "/")
  320. if len(pieces) == 2 {
  321. sh.baseUsers(w, r)
  322. return
  323. }
  324. if len(pieces) != 3 {
  325. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  326. return
  327. }
  328. sh.forUser(w, r, pieces[2])
  329. }
  330. func (sh *authHandler) forUser(w http.ResponseWriter, r *http.Request, user string) {
  331. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  332. return
  333. }
  334. if !hasRootAccess(sh.sec, r) {
  335. writeNoAuth(w, r)
  336. return
  337. }
  338. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  339. w.Header().Set("Content-Type", "application/json")
  340. switch r.Method {
  341. case "GET":
  342. u, err := sh.sec.GetUser(user)
  343. if err != nil {
  344. writeError(w, r, err)
  345. return
  346. }
  347. err = r.ParseForm()
  348. if err != nil {
  349. writeError(w, r, err)
  350. return
  351. }
  352. uwr := userWithRoles{User: u.User}
  353. for _, roleName := range u.Roles {
  354. var role auth.Role
  355. role, err = sh.sec.GetRole(roleName)
  356. if err != nil {
  357. writeError(w, r, err)
  358. return
  359. }
  360. uwr.Roles = append(uwr.Roles, role)
  361. }
  362. err = json.NewEncoder(w).Encode(uwr)
  363. if err != nil {
  364. plog.Warningf("forUser error encoding on %s", r.URL)
  365. return
  366. }
  367. return
  368. case "PUT":
  369. var u auth.User
  370. err := json.NewDecoder(r.Body).Decode(&u)
  371. if err != nil {
  372. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  373. return
  374. }
  375. if u.User != user {
  376. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "User JSON name does not match the name in the URL"))
  377. return
  378. }
  379. var (
  380. out auth.User
  381. created bool
  382. )
  383. if len(u.Grant) == 0 && len(u.Revoke) == 0 {
  384. // create or update
  385. if len(u.Roles) != 0 {
  386. out, err = sh.sec.CreateUser(u)
  387. } else {
  388. // if user passes in both password and roles, we are unsure about his/her
  389. // intention.
  390. out, created, err = sh.sec.CreateOrUpdateUser(u)
  391. }
  392. if err != nil {
  393. writeError(w, r, err)
  394. return
  395. }
  396. } else {
  397. // update case
  398. if len(u.Roles) != 0 {
  399. writeError(w, r, httptypes.NewHTTPError(http.StatusBadRequest, "User JSON contains both roles and grant/revoke"))
  400. return
  401. }
  402. out, err = sh.sec.UpdateUser(u)
  403. if err != nil {
  404. writeError(w, r, err)
  405. return
  406. }
  407. }
  408. if created {
  409. w.WriteHeader(http.StatusCreated)
  410. } else {
  411. w.WriteHeader(http.StatusOK)
  412. }
  413. out.Password = ""
  414. err = json.NewEncoder(w).Encode(out)
  415. if err != nil {
  416. plog.Warningf("forUser error encoding on %s", r.URL)
  417. return
  418. }
  419. return
  420. case "DELETE":
  421. err := sh.sec.DeleteUser(user)
  422. if err != nil {
  423. writeError(w, r, err)
  424. return
  425. }
  426. }
  427. }
  428. type enabled struct {
  429. Enabled bool `json:"enabled"`
  430. }
  431. func (sh *authHandler) enableDisable(w http.ResponseWriter, r *http.Request) {
  432. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  433. return
  434. }
  435. if !hasWriteRootAccess(sh.sec, r) {
  436. writeNoAuth(w, r)
  437. return
  438. }
  439. w.Header().Set("X-Etcd-Cluster-ID", sh.cluster.ID().String())
  440. w.Header().Set("Content-Type", "application/json")
  441. isEnabled := sh.sec.AuthEnabled()
  442. switch r.Method {
  443. case "GET":
  444. jsonDict := enabled{isEnabled}
  445. err := json.NewEncoder(w).Encode(jsonDict)
  446. if err != nil {
  447. plog.Warningf("error encoding auth state on %s", r.URL)
  448. }
  449. case "PUT":
  450. err := sh.sec.EnableAuth()
  451. if err != nil {
  452. writeError(w, r, err)
  453. return
  454. }
  455. case "DELETE":
  456. err := sh.sec.DisableAuth()
  457. if err != nil {
  458. writeError(w, r, err)
  459. return
  460. }
  461. }
  462. }