auth.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "net/http"
  19. "path"
  20. "reflect"
  21. "sort"
  22. "strings"
  23. "sync"
  24. "time"
  25. "github.com/coreos/etcd/Godeps/_workspace/src/github.com/coreos/pkg/capnslog"
  26. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/crypto/bcrypt"
  27. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  28. etcderr "github.com/coreos/etcd/error"
  29. "github.com/coreos/etcd/etcdserver"
  30. "github.com/coreos/etcd/etcdserver/etcdserverpb"
  31. "github.com/coreos/etcd/pkg/types"
  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. mu sync.Mutex // protect enabled
  91. enabled *bool
  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. _, err := s.GetUser("root")
  379. if err != nil {
  380. return authErr(http.StatusConflict, "No root user available, please create one")
  381. }
  382. _, err = s.GetRole(GuestRoleName)
  383. if err != nil {
  384. plog.Printf("no guest role access found, creating default")
  385. err := s.CreateRole(guestRole)
  386. if err != nil {
  387. plog.Errorf("error creating guest role. aborting auth enable.")
  388. return err
  389. }
  390. }
  391. err = s.enableAuth()
  392. if err == nil {
  393. b := true
  394. s.enabled = &b
  395. plog.Noticef("auth: enabled auth")
  396. } else {
  397. plog.Errorf("error enabling auth (%v)", err)
  398. }
  399. return err
  400. }
  401. func (s *store) DisableAuth() error {
  402. if !s.AuthEnabled() {
  403. return authErr(http.StatusConflict, "already disabled")
  404. }
  405. s.mu.Lock()
  406. defer s.mu.Unlock()
  407. err := s.disableAuth()
  408. if err == nil {
  409. b := false
  410. s.enabled = &b
  411. plog.Noticef("auth: disabled auth")
  412. } else {
  413. plog.Errorf("error disabling auth (%v)", err)
  414. }
  415. return err
  416. }
  417. // merge applies the properties of the passed-in User to the User on which it
  418. // is called and returns a new User with these modifications applied. Think of
  419. // all Users as immutable sets of data. Merge allows you to perform the set
  420. // operations (desired grants and revokes) atomically
  421. func (u User) merge(n User) (User, error) {
  422. var out User
  423. if u.User != n.User {
  424. return out, authErr(http.StatusConflict, "Merging user data with conflicting usernames: %s %s", u.User, n.User)
  425. }
  426. out.User = u.User
  427. if n.Password != "" {
  428. out.Password = n.Password
  429. } else {
  430. out.Password = u.Password
  431. }
  432. currentRoles := types.NewUnsafeSet(u.Roles...)
  433. for _, g := range n.Grant {
  434. if currentRoles.Contains(g) {
  435. plog.Noticef("granting duplicate role %s for user %s", g, n.User)
  436. return User{}, authErr(http.StatusConflict, fmt.Sprintf("Granting duplicate role %s for user %s", g, n.User))
  437. }
  438. currentRoles.Add(g)
  439. }
  440. for _, r := range n.Revoke {
  441. if !currentRoles.Contains(r) {
  442. plog.Noticef("revoking ungranted role %s for user %s", r, n.User)
  443. return User{}, authErr(http.StatusConflict, fmt.Sprintf("Revoking ungranted role %s for user %s", r, n.User))
  444. }
  445. currentRoles.Remove(r)
  446. }
  447. out.Roles = currentRoles.Values()
  448. sort.Strings(out.Roles)
  449. return out, nil
  450. }
  451. // merge for a role works the same as User above -- atomic Role application to
  452. // each of the substructures.
  453. func (r Role) merge(n Role) (Role, error) {
  454. var out Role
  455. var err error
  456. if r.Role != n.Role {
  457. return out, authErr(http.StatusConflict, "Merging role with conflicting names: %s %s", r.Role, n.Role)
  458. }
  459. out.Role = r.Role
  460. out.Permissions, err = r.Permissions.Grant(n.Grant)
  461. if err != nil {
  462. return out, err
  463. }
  464. out.Permissions, err = out.Permissions.Revoke(n.Revoke)
  465. if err != nil {
  466. return out, err
  467. }
  468. return out, nil
  469. }
  470. func (r Role) HasKeyAccess(key string, write bool) bool {
  471. if r.Role == RootRoleName {
  472. return true
  473. }
  474. return r.Permissions.KV.HasAccess(key, write)
  475. }
  476. func (r Role) HasRecursiveAccess(key string, write bool) bool {
  477. if r.Role == RootRoleName {
  478. return true
  479. }
  480. return r.Permissions.KV.HasRecursiveAccess(key, write)
  481. }
  482. // Grant adds a set of permissions to the permission object on which it is called,
  483. // returning a new permission object.
  484. func (p Permissions) Grant(n *Permissions) (Permissions, error) {
  485. var out Permissions
  486. var err error
  487. if n == nil {
  488. return p, nil
  489. }
  490. out.KV, err = p.KV.Grant(n.KV)
  491. return out, err
  492. }
  493. // Revoke removes a set of permissions to the permission object on which it is called,
  494. // returning a new permission object.
  495. func (p Permissions) Revoke(n *Permissions) (Permissions, error) {
  496. var out Permissions
  497. var err error
  498. if n == nil {
  499. return p, nil
  500. }
  501. out.KV, err = p.KV.Revoke(n.KV)
  502. return out, err
  503. }
  504. // Grant adds a set of permissions to the permission object on which it is called,
  505. // returning a new permission object.
  506. func (rw RWPermission) Grant(n RWPermission) (RWPermission, error) {
  507. var out RWPermission
  508. currentRead := types.NewUnsafeSet(rw.Read...)
  509. for _, r := range n.Read {
  510. if currentRead.Contains(r) {
  511. return out, authErr(http.StatusConflict, "Granting duplicate read permission %s", r)
  512. }
  513. currentRead.Add(r)
  514. }
  515. currentWrite := types.NewUnsafeSet(rw.Write...)
  516. for _, w := range n.Write {
  517. if currentWrite.Contains(w) {
  518. return out, authErr(http.StatusConflict, "Granting duplicate write permission %s", w)
  519. }
  520. currentWrite.Add(w)
  521. }
  522. out.Read = currentRead.Values()
  523. out.Write = currentWrite.Values()
  524. sort.Strings(out.Read)
  525. sort.Strings(out.Write)
  526. return out, nil
  527. }
  528. // Revoke removes a set of permissions to the permission object on which it is called,
  529. // returning a new permission object.
  530. func (rw RWPermission) Revoke(n RWPermission) (RWPermission, error) {
  531. var out RWPermission
  532. currentRead := types.NewUnsafeSet(rw.Read...)
  533. for _, r := range n.Read {
  534. if !currentRead.Contains(r) {
  535. plog.Noticef("revoking ungranted read permission %s", r)
  536. continue
  537. }
  538. currentRead.Remove(r)
  539. }
  540. currentWrite := types.NewUnsafeSet(rw.Write...)
  541. for _, w := range n.Write {
  542. if !currentWrite.Contains(w) {
  543. plog.Noticef("revoking ungranted write permission %s", w)
  544. continue
  545. }
  546. currentWrite.Remove(w)
  547. }
  548. out.Read = currentRead.Values()
  549. out.Write = currentWrite.Values()
  550. sort.Strings(out.Read)
  551. sort.Strings(out.Write)
  552. return out, nil
  553. }
  554. func (rw RWPermission) HasAccess(key string, write bool) bool {
  555. var list []string
  556. if write {
  557. list = rw.Write
  558. } else {
  559. list = rw.Read
  560. }
  561. for _, pat := range list {
  562. match, err := simpleMatch(pat, key)
  563. if err == nil && match {
  564. return true
  565. }
  566. }
  567. return false
  568. }
  569. func (rw RWPermission) HasRecursiveAccess(key string, write bool) bool {
  570. list := rw.Read
  571. if write {
  572. list = rw.Write
  573. }
  574. for _, pat := range list {
  575. match, err := prefixMatch(pat, key)
  576. if err == nil && match {
  577. return true
  578. }
  579. }
  580. return false
  581. }
  582. func simpleMatch(pattern string, key string) (match bool, err error) {
  583. if pattern[len(pattern)-1] == '*' {
  584. return strings.HasPrefix(key, pattern[:len(pattern)-1]), nil
  585. }
  586. return key == pattern, nil
  587. }
  588. func prefixMatch(pattern string, key string) (match bool, err error) {
  589. if pattern[len(pattern)-1] != '*' {
  590. return false, nil
  591. }
  592. return strings.HasPrefix(key, pattern[:len(pattern)-1]), nil
  593. }
  594. func attachRootRole(u User) User {
  595. inRoles := false
  596. for _, r := range u.Roles {
  597. if r == RootRoleName {
  598. inRoles = true
  599. break
  600. }
  601. }
  602. if !inRoles {
  603. u.Roles = append(u.Roles, RootRoleName)
  604. }
  605. return u
  606. }