auth.go 17 KB

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