client_auth.go 13 KB

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