auth.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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 auth implements etcd authentication.
  15. package auth
  16. import (
  17. "encoding/json"
  18. "fmt"
  19. "net/http"
  20. "path"
  21. "reflect"
  22. "sort"
  23. "strings"
  24. "time"
  25. etcderr "github.com/coreos/etcd/error"
  26. "github.com/coreos/etcd/etcdserver"
  27. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  28. "github.com/coreos/etcd/pkg/types"
  29. "github.com/coreos/pkg/capnslog"
  30. "golang.org/x/crypto/bcrypt"
  31. "golang.org/x/net/context"
  32. )
  33. const (
  34. // StorePermsPrefix is the internal prefix of the storage layer dedicated to storing user data.
  35. StorePermsPrefix = "/2"
  36. // RootRoleName is the name of the ROOT role, with privileges to manage the cluster.
  37. RootRoleName = "root"
  38. // GuestRoleName is the name of the role that defines the privileges of an unauthenticated user.
  39. GuestRoleName = "guest"
  40. )
  41. var (
  42. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdserver/auth")
  43. )
  44. var rootRole = Role{
  45. Role: RootRoleName,
  46. Permissions: Permissions{
  47. KV: RWPermission{
  48. Read: []string{"/*"},
  49. Write: []string{"/*"},
  50. },
  51. },
  52. }
  53. var guestRole = Role{
  54. Role: GuestRoleName,
  55. Permissions: Permissions{
  56. KV: RWPermission{
  57. Read: []string{"/*"},
  58. Write: []string{"/*"},
  59. },
  60. },
  61. }
  62. type doer interface {
  63. Do(context.Context, etcdserverpb.Request) (etcdserver.Response, error)
  64. }
  65. type Store interface {
  66. AllUsers() ([]string, error)
  67. GetUser(name string) (User, error)
  68. CreateOrUpdateUser(user User) (out User, created bool, err error)
  69. CreateUser(user User) (User, error)
  70. DeleteUser(name string) error
  71. UpdateUser(user User) (User, error)
  72. AllRoles() ([]string, error)
  73. GetRole(name string) (Role, error)
  74. CreateRole(role Role) error
  75. DeleteRole(name string) error
  76. UpdateRole(role Role) (Role, error)
  77. AuthEnabled() bool
  78. EnableAuth() error
  79. DisableAuth() error
  80. PasswordStore
  81. }
  82. type PasswordStore interface {
  83. CheckPassword(user User, password string) bool
  84. HashPassword(password string) (string, error)
  85. }
  86. type store struct {
  87. server doer
  88. timeout time.Duration
  89. ensuredOnce bool
  90. PasswordStore
  91. }
  92. type User struct {
  93. User string `json:"user"`
  94. Password string `json:"password,omitempty"`
  95. Roles []string `json:"roles"`
  96. Grant []string `json:"grant,omitempty"`
  97. Revoke []string `json:"revoke,omitempty"`
  98. }
  99. type Role struct {
  100. Role string `json:"role"`
  101. Permissions Permissions `json:"permissions"`
  102. Grant *Permissions `json:"grant,omitempty"`
  103. Revoke *Permissions `json:"revoke,omitempty"`
  104. }
  105. type Permissions struct {
  106. KV RWPermission `json:"kv"`
  107. }
  108. func (p *Permissions) IsEmpty() bool {
  109. return p == nil || (len(p.KV.Read) == 0 && len(p.KV.Write) == 0)
  110. }
  111. type RWPermission struct {
  112. Read []string `json:"read"`
  113. Write []string `json:"write"`
  114. }
  115. type Error struct {
  116. Status int
  117. Errmsg string
  118. }
  119. func (ae Error) Error() string { return ae.Errmsg }
  120. func (ae Error) HTTPStatus() int { return ae.Status }
  121. func authErr(hs int, s string, v ...interface{}) Error {
  122. return Error{Status: hs, Errmsg: fmt.Sprintf("auth: "+s, v...)}
  123. }
  124. func NewStore(server doer, timeout time.Duration) Store {
  125. s := &store{
  126. server: server,
  127. timeout: timeout,
  128. PasswordStore: passwordStore{},
  129. }
  130. return s
  131. }
  132. // passwordStore implements PasswordStore using bcrypt to hash user passwords
  133. type passwordStore struct{}
  134. func (_ passwordStore) CheckPassword(user User, password string) bool {
  135. err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password))
  136. return err == nil
  137. }
  138. func (_ passwordStore) HashPassword(password string) (string, error) {
  139. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  140. return string(hash), err
  141. }
  142. func (s *store) AllUsers() ([]string, error) {
  143. resp, err := s.requestResource("/users/", false, false)
  144. if err != nil {
  145. if e, ok := err.(*etcderr.Error); ok {
  146. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  147. return []string{}, nil
  148. }
  149. }
  150. return nil, err
  151. }
  152. var nodes []string
  153. for _, n := range resp.Event.Node.Nodes {
  154. _, user := path.Split(n.Key)
  155. nodes = append(nodes, user)
  156. }
  157. sort.Strings(nodes)
  158. return nodes, nil
  159. }
  160. func (s *store) GetUser(name string) (User, error) { return s.getUser(name, false) }
  161. // CreateOrUpdateUser should be only used for creating the new user or when you are not
  162. // sure if it is a create or update. (When only password is passed in, we are not sure
  163. // if it is a update or create)
  164. func (s *store) CreateOrUpdateUser(user User) (out User, created bool, err error) {
  165. _, err = s.getUser(user.User, true)
  166. if err == nil {
  167. out, err = s.UpdateUser(user)
  168. return out, false, err
  169. }
  170. u, err := s.CreateUser(user)
  171. return u, true, err
  172. }
  173. func (s *store) CreateUser(user User) (User, error) {
  174. // Attach root role to root user.
  175. if user.User == "root" {
  176. user = attachRootRole(user)
  177. }
  178. u, err := s.createUserInternal(user)
  179. if err == nil {
  180. plog.Noticef("created user %s", user.User)
  181. }
  182. return u, err
  183. }
  184. func (s *store) createUserInternal(user User) (User, error) {
  185. if user.Password == "" {
  186. return user, authErr(http.StatusBadRequest, "Cannot create user %s with an empty password", user.User)
  187. }
  188. hash, err := s.HashPassword(user.Password)
  189. if err != nil {
  190. return user, err
  191. }
  192. user.Password = hash
  193. _, err = s.createResource("/users/"+user.User, user)
  194. if err != nil {
  195. if e, ok := err.(*etcderr.Error); ok {
  196. if e.ErrorCode == etcderr.EcodeNodeExist {
  197. return user, authErr(http.StatusConflict, "User %s already exists.", user.User)
  198. }
  199. }
  200. }
  201. return user, err
  202. }
  203. func (s *store) DeleteUser(name string) error {
  204. if s.AuthEnabled() && name == "root" {
  205. return authErr(http.StatusForbidden, "Cannot delete root user while auth is enabled.")
  206. }
  207. _, err := s.deleteResource("/users/" + name)
  208. if err != nil {
  209. if e, ok := err.(*etcderr.Error); ok {
  210. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  211. return authErr(http.StatusNotFound, "User %s does not exist", name)
  212. }
  213. }
  214. return err
  215. }
  216. plog.Noticef("deleted user %s", name)
  217. return nil
  218. }
  219. func (s *store) UpdateUser(user User) (User, error) {
  220. old, err := s.getUser(user.User, true)
  221. if err != nil {
  222. if e, ok := err.(*etcderr.Error); ok {
  223. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  224. return user, authErr(http.StatusNotFound, "User %s doesn't exist.", user.User)
  225. }
  226. }
  227. return old, err
  228. }
  229. newUser, err := old.merge(user, s.PasswordStore)
  230. if err != nil {
  231. return old, err
  232. }
  233. if reflect.DeepEqual(old, newUser) {
  234. return old, authErr(http.StatusBadRequest, "User not updated. Use grant/revoke/password to update the user.")
  235. }
  236. _, err = s.updateResource("/users/"+user.User, newUser)
  237. if err == nil {
  238. plog.Noticef("updated user %s", user.User)
  239. }
  240. return newUser, err
  241. }
  242. func (s *store) AllRoles() ([]string, error) {
  243. nodes := []string{RootRoleName}
  244. resp, err := s.requestResource("/roles/", false, false)
  245. if err != nil {
  246. if e, ok := err.(*etcderr.Error); ok {
  247. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  248. return nodes, nil
  249. }
  250. }
  251. return nil, err
  252. }
  253. for _, n := range resp.Event.Node.Nodes {
  254. _, role := path.Split(n.Key)
  255. nodes = append(nodes, role)
  256. }
  257. sort.Strings(nodes)
  258. return nodes, nil
  259. }
  260. func (s *store) GetRole(name string) (Role, error) { return s.getRole(name, false) }
  261. func (s *store) CreateRole(role Role) error {
  262. if role.Role == RootRoleName {
  263. return authErr(http.StatusForbidden, "Cannot modify role %s: is root role.", role.Role)
  264. }
  265. _, err := s.createResource("/roles/"+role.Role, role)
  266. if err != nil {
  267. if e, ok := err.(*etcderr.Error); ok {
  268. if e.ErrorCode == etcderr.EcodeNodeExist {
  269. return authErr(http.StatusConflict, "Role %s already exists.", role.Role)
  270. }
  271. }
  272. }
  273. if err == nil {
  274. plog.Noticef("created new role %s", role.Role)
  275. }
  276. return err
  277. }
  278. func (s *store) DeleteRole(name string) error {
  279. if name == RootRoleName {
  280. return authErr(http.StatusForbidden, "Cannot modify role %s: is root role.", name)
  281. }
  282. _, err := s.deleteResource("/roles/" + name)
  283. if err != nil {
  284. if e, ok := err.(*etcderr.Error); ok {
  285. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  286. return authErr(http.StatusNotFound, "Role %s doesn't exist.", name)
  287. }
  288. }
  289. }
  290. if err == nil {
  291. plog.Noticef("deleted role %s", name)
  292. }
  293. return err
  294. }
  295. func (s *store) UpdateRole(role Role) (Role, error) {
  296. if role.Role == RootRoleName {
  297. return Role{}, authErr(http.StatusForbidden, "Cannot modify role %s: is root role.", role.Role)
  298. }
  299. old, err := s.getRole(role.Role, true)
  300. if err != nil {
  301. if e, ok := err.(*etcderr.Error); ok {
  302. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  303. return role, authErr(http.StatusNotFound, "Role %s doesn't exist.", role.Role)
  304. }
  305. }
  306. return old, err
  307. }
  308. newRole, err := old.merge(role)
  309. if err != nil {
  310. return old, err
  311. }
  312. if reflect.DeepEqual(old, newRole) {
  313. return old, authErr(http.StatusBadRequest, "Role not updated. Use grant/revoke to update the role.")
  314. }
  315. _, err = s.updateResource("/roles/"+role.Role, newRole)
  316. if err == nil {
  317. plog.Noticef("updated role %s", role.Role)
  318. }
  319. return newRole, err
  320. }
  321. func (s *store) AuthEnabled() bool {
  322. return s.detectAuth()
  323. }
  324. func (s *store) EnableAuth() error {
  325. if s.AuthEnabled() {
  326. return authErr(http.StatusConflict, "already enabled")
  327. }
  328. if _, err := s.getUser("root", true); err != nil {
  329. return authErr(http.StatusConflict, "No root user available, please create one")
  330. }
  331. if _, err := s.getRole(GuestRoleName, true); err != nil {
  332. plog.Printf("no guest role access found, creating default")
  333. if err := s.CreateRole(guestRole); err != nil {
  334. plog.Errorf("error creating guest role. aborting auth enable.")
  335. return err
  336. }
  337. }
  338. if err := s.enableAuth(); err != nil {
  339. plog.Errorf("error enabling auth (%v)", err)
  340. return err
  341. }
  342. plog.Noticef("auth: enabled auth")
  343. return nil
  344. }
  345. func (s *store) DisableAuth() error {
  346. if !s.AuthEnabled() {
  347. return authErr(http.StatusConflict, "already disabled")
  348. }
  349. err := s.disableAuth()
  350. if err == nil {
  351. plog.Noticef("auth: disabled auth")
  352. } else {
  353. plog.Errorf("error disabling auth (%v)", err)
  354. }
  355. return err
  356. }
  357. // merge applies the properties of the passed-in User to the User on which it
  358. // is called and returns a new User with these modifications applied. Think of
  359. // all Users as immutable sets of data. Merge allows you to perform the set
  360. // operations (desired grants and revokes) atomically
  361. func (ou User) merge(nu User, s PasswordStore) (User, error) {
  362. var out User
  363. if ou.User != nu.User {
  364. return out, authErr(http.StatusConflict, "Merging user data with conflicting usernames: %s %s", ou.User, nu.User)
  365. }
  366. out.User = ou.User
  367. if nu.Password != "" {
  368. hash, err := s.HashPassword(nu.Password)
  369. if err != nil {
  370. return ou, err
  371. }
  372. out.Password = hash
  373. } else {
  374. out.Password = ou.Password
  375. }
  376. currentRoles := types.NewUnsafeSet(ou.Roles...)
  377. for _, g := range nu.Grant {
  378. if currentRoles.Contains(g) {
  379. plog.Noticef("granting duplicate role %s for user %s", g, nu.User)
  380. return User{}, authErr(http.StatusConflict, fmt.Sprintf("Granting duplicate role %s for user %s", g, nu.User))
  381. }
  382. currentRoles.Add(g)
  383. }
  384. for _, r := range nu.Revoke {
  385. if !currentRoles.Contains(r) {
  386. plog.Noticef("revoking ungranted role %s for user %s", r, nu.User)
  387. return User{}, authErr(http.StatusConflict, fmt.Sprintf("Revoking ungranted role %s for user %s", r, nu.User))
  388. }
  389. currentRoles.Remove(r)
  390. }
  391. out.Roles = currentRoles.Values()
  392. sort.Strings(out.Roles)
  393. return out, nil
  394. }
  395. // merge for a role works the same as User above -- atomic Role application to
  396. // each of the substructures.
  397. func (r Role) merge(n Role) (Role, error) {
  398. var out Role
  399. var err error
  400. if r.Role != n.Role {
  401. return out, authErr(http.StatusConflict, "Merging role with conflicting names: %s %s", r.Role, n.Role)
  402. }
  403. out.Role = r.Role
  404. out.Permissions, err = r.Permissions.Grant(n.Grant)
  405. if err != nil {
  406. return out, err
  407. }
  408. out.Permissions, err = out.Permissions.Revoke(n.Revoke)
  409. return out, err
  410. }
  411. func (r Role) HasKeyAccess(key string, write bool) bool {
  412. if r.Role == RootRoleName {
  413. return true
  414. }
  415. return r.Permissions.KV.HasAccess(key, write)
  416. }
  417. func (r Role) HasRecursiveAccess(key string, write bool) bool {
  418. if r.Role == RootRoleName {
  419. return true
  420. }
  421. return r.Permissions.KV.HasRecursiveAccess(key, write)
  422. }
  423. // Grant adds a set of permissions to the permission object on which it is called,
  424. // returning a new permission object.
  425. func (p Permissions) Grant(n *Permissions) (Permissions, error) {
  426. var out Permissions
  427. var err error
  428. if n == nil {
  429. return p, nil
  430. }
  431. out.KV, err = p.KV.Grant(n.KV)
  432. return out, err
  433. }
  434. // Revoke removes a set of permissions to the permission object on which it is called,
  435. // returning a new permission object.
  436. func (p Permissions) Revoke(n *Permissions) (Permissions, error) {
  437. var out Permissions
  438. var err error
  439. if n == nil {
  440. return p, nil
  441. }
  442. out.KV, err = p.KV.Revoke(n.KV)
  443. return out, err
  444. }
  445. // Grant adds a set of permissions to the permission object on which it is called,
  446. // returning a new permission object.
  447. func (rw RWPermission) Grant(n RWPermission) (RWPermission, error) {
  448. var out RWPermission
  449. currentRead := types.NewUnsafeSet(rw.Read...)
  450. for _, r := range n.Read {
  451. if currentRead.Contains(r) {
  452. return out, authErr(http.StatusConflict, "Granting duplicate read permission %s", r)
  453. }
  454. currentRead.Add(r)
  455. }
  456. currentWrite := types.NewUnsafeSet(rw.Write...)
  457. for _, w := range n.Write {
  458. if currentWrite.Contains(w) {
  459. return out, authErr(http.StatusConflict, "Granting duplicate write permission %s", w)
  460. }
  461. currentWrite.Add(w)
  462. }
  463. out.Read = currentRead.Values()
  464. out.Write = currentWrite.Values()
  465. sort.Strings(out.Read)
  466. sort.Strings(out.Write)
  467. return out, nil
  468. }
  469. // Revoke removes a set of permissions to the permission object on which it is called,
  470. // returning a new permission object.
  471. func (rw RWPermission) Revoke(n RWPermission) (RWPermission, error) {
  472. var out RWPermission
  473. currentRead := types.NewUnsafeSet(rw.Read...)
  474. for _, r := range n.Read {
  475. if !currentRead.Contains(r) {
  476. plog.Noticef("revoking ungranted read permission %s", r)
  477. continue
  478. }
  479. currentRead.Remove(r)
  480. }
  481. currentWrite := types.NewUnsafeSet(rw.Write...)
  482. for _, w := range n.Write {
  483. if !currentWrite.Contains(w) {
  484. plog.Noticef("revoking ungranted write permission %s", w)
  485. continue
  486. }
  487. currentWrite.Remove(w)
  488. }
  489. out.Read = currentRead.Values()
  490. out.Write = currentWrite.Values()
  491. sort.Strings(out.Read)
  492. sort.Strings(out.Write)
  493. return out, nil
  494. }
  495. func (rw RWPermission) HasAccess(key string, write bool) bool {
  496. var list []string
  497. if write {
  498. list = rw.Write
  499. } else {
  500. list = rw.Read
  501. }
  502. for _, pat := range list {
  503. match, err := simpleMatch(pat, key)
  504. if err == nil && match {
  505. return true
  506. }
  507. }
  508. return false
  509. }
  510. func (rw RWPermission) HasRecursiveAccess(key string, write bool) bool {
  511. list := rw.Read
  512. if write {
  513. list = rw.Write
  514. }
  515. for _, pat := range list {
  516. match, err := prefixMatch(pat, key)
  517. if err == nil && match {
  518. return true
  519. }
  520. }
  521. return false
  522. }
  523. func simpleMatch(pattern string, key string) (match bool, err error) {
  524. if pattern[len(pattern)-1] == '*' {
  525. return strings.HasPrefix(key, pattern[:len(pattern)-1]), nil
  526. }
  527. return key == pattern, nil
  528. }
  529. func prefixMatch(pattern string, key string) (match bool, err error) {
  530. if pattern[len(pattern)-1] != '*' {
  531. return false, nil
  532. }
  533. return strings.HasPrefix(key, pattern[:len(pattern)-1]), nil
  534. }
  535. func attachRootRole(u User) User {
  536. inRoles := false
  537. for _, r := range u.Roles {
  538. if r == RootRoleName {
  539. inRoles = true
  540. break
  541. }
  542. }
  543. if !inRoles {
  544. u.Roles = append(u.Roles, RootRoleName)
  545. }
  546. return u
  547. }
  548. func (s *store) getUser(name string, quorum bool) (User, error) {
  549. resp, err := s.requestResource("/users/"+name, false, quorum)
  550. if err != nil {
  551. if e, ok := err.(*etcderr.Error); ok {
  552. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  553. return User{}, authErr(http.StatusNotFound, "User %s does not exist.", name)
  554. }
  555. }
  556. return User{}, err
  557. }
  558. var u User
  559. err = json.Unmarshal([]byte(*resp.Event.Node.Value), &u)
  560. if err != nil {
  561. return u, err
  562. }
  563. // Attach root role to root user.
  564. if u.User == "root" {
  565. u = attachRootRole(u)
  566. }
  567. return u, nil
  568. }
  569. func (s *store) getRole(name string, quorum bool) (Role, error) {
  570. if name == RootRoleName {
  571. return rootRole, nil
  572. }
  573. resp, err := s.requestResource("/roles/"+name, false, quorum)
  574. if err != nil {
  575. if e, ok := err.(*etcderr.Error); ok {
  576. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  577. return Role{}, authErr(http.StatusNotFound, "Role %s does not exist.", name)
  578. }
  579. }
  580. return Role{}, err
  581. }
  582. var r Role
  583. err = json.Unmarshal([]byte(*resp.Event.Node.Value), &r)
  584. return r, err
  585. }