client_auth.go 13 KB

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