auth.go 17 KB

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