auth.go 17 KB

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