auth.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. 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)
  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. return r, err
  301. }
  302. func (s *store) CreateRole(role Role) error {
  303. if role.Role == RootRoleName {
  304. return authErr(http.StatusForbidden, "Cannot modify role %s: is root role.", role.Role)
  305. }
  306. _, err := s.createResource("/roles/"+role.Role, role)
  307. if err != nil {
  308. if e, ok := err.(*etcderr.Error); ok {
  309. if e.ErrorCode == etcderr.EcodeNodeExist {
  310. return authErr(http.StatusConflict, "Role %s already exists.", role.Role)
  311. }
  312. }
  313. }
  314. if err == nil {
  315. plog.Noticef("created new role %s", role.Role)
  316. }
  317. return err
  318. }
  319. func (s *store) DeleteRole(name string) error {
  320. if name == RootRoleName {
  321. return authErr(http.StatusForbidden, "Cannot modify role %s: is root role.", name)
  322. }
  323. _, err := s.deleteResource("/roles/" + name)
  324. if err != nil {
  325. if e, ok := err.(*etcderr.Error); ok {
  326. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  327. return authErr(http.StatusNotFound, "Role %s doesn't exist.", name)
  328. }
  329. }
  330. }
  331. if err == nil {
  332. plog.Noticef("deleted role %s", name)
  333. }
  334. return err
  335. }
  336. func (s *store) UpdateRole(role Role) (Role, error) {
  337. if role.Role == RootRoleName {
  338. return Role{}, authErr(http.StatusForbidden, "Cannot modify role %s: is root role.", role.Role)
  339. }
  340. old, err := s.GetRole(role.Role)
  341. if err != nil {
  342. if e, ok := err.(*etcderr.Error); ok {
  343. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  344. return role, authErr(http.StatusNotFound, "Role %s doesn't exist.", role.Role)
  345. }
  346. }
  347. return old, err
  348. }
  349. newRole, err := old.merge(role)
  350. if err != nil {
  351. return old, err
  352. }
  353. if reflect.DeepEqual(old, newRole) {
  354. return old, authErr(http.StatusBadRequest, "Role not updated. Use grant/revoke to update the role.")
  355. }
  356. _, err = s.updateResource("/roles/"+role.Role, newRole)
  357. if err == nil {
  358. plog.Noticef("updated role %s", role.Role)
  359. }
  360. return newRole, err
  361. }
  362. func (s *store) AuthEnabled() bool {
  363. return s.detectAuth()
  364. }
  365. func (s *store) EnableAuth() error {
  366. if s.AuthEnabled() {
  367. return authErr(http.StatusConflict, "already enabled")
  368. }
  369. if _, err := s.GetUser("root"); err != nil {
  370. return authErr(http.StatusConflict, "No root user available, please create one")
  371. }
  372. if _, err := s.GetRole(GuestRoleName); err != nil {
  373. plog.Printf("no guest role access found, creating default")
  374. if err := s.CreateRole(guestRole); err != nil {
  375. plog.Errorf("error creating guest role. aborting auth enable.")
  376. return err
  377. }
  378. }
  379. if err := s.enableAuth(); err != nil {
  380. plog.Errorf("error enabling auth (%v)", err)
  381. return err
  382. }
  383. plog.Noticef("auth: enabled auth")
  384. return nil
  385. }
  386. func (s *store) DisableAuth() error {
  387. if !s.AuthEnabled() {
  388. return authErr(http.StatusConflict, "already disabled")
  389. }
  390. err := s.disableAuth()
  391. if err == nil {
  392. plog.Noticef("auth: disabled auth")
  393. } else {
  394. plog.Errorf("error disabling auth (%v)", err)
  395. }
  396. return err
  397. }
  398. // merge applies the properties of the passed-in User to the User on which it
  399. // is called and returns a new User with these modifications applied. Think of
  400. // all Users as immutable sets of data. Merge allows you to perform the set
  401. // operations (desired grants and revokes) atomically
  402. func (u User) merge(n User) (User, error) {
  403. var out User
  404. if u.User != n.User {
  405. return out, authErr(http.StatusConflict, "Merging user data with conflicting usernames: %s %s", u.User, n.User)
  406. }
  407. out.User = u.User
  408. if n.Password != "" {
  409. out.Password = n.Password
  410. } else {
  411. out.Password = u.Password
  412. }
  413. currentRoles := types.NewUnsafeSet(u.Roles...)
  414. for _, g := range n.Grant {
  415. if currentRoles.Contains(g) {
  416. plog.Noticef("granting duplicate role %s for user %s", g, n.User)
  417. return User{}, authErr(http.StatusConflict, fmt.Sprintf("Granting duplicate role %s for user %s", g, n.User))
  418. }
  419. currentRoles.Add(g)
  420. }
  421. for _, r := range n.Revoke {
  422. if !currentRoles.Contains(r) {
  423. plog.Noticef("revoking ungranted role %s for user %s", r, n.User)
  424. return User{}, authErr(http.StatusConflict, fmt.Sprintf("Revoking ungranted role %s for user %s", r, n.User))
  425. }
  426. currentRoles.Remove(r)
  427. }
  428. out.Roles = currentRoles.Values()
  429. sort.Strings(out.Roles)
  430. return out, nil
  431. }
  432. // merge for a role works the same as User above -- atomic Role application to
  433. // each of the substructures.
  434. func (r Role) merge(n Role) (Role, error) {
  435. var out Role
  436. var err error
  437. if r.Role != n.Role {
  438. return out, authErr(http.StatusConflict, "Merging role with conflicting names: %s %s", r.Role, n.Role)
  439. }
  440. out.Role = r.Role
  441. out.Permissions, err = r.Permissions.Grant(n.Grant)
  442. if err != nil {
  443. return out, err
  444. }
  445. out.Permissions, err = out.Permissions.Revoke(n.Revoke)
  446. return out, err
  447. }
  448. func (r Role) HasKeyAccess(key string, write bool) bool {
  449. if r.Role == RootRoleName {
  450. return true
  451. }
  452. return r.Permissions.KV.HasAccess(key, write)
  453. }
  454. func (r Role) HasRecursiveAccess(key string, write bool) bool {
  455. if r.Role == RootRoleName {
  456. return true
  457. }
  458. return r.Permissions.KV.HasRecursiveAccess(key, write)
  459. }
  460. // Grant adds a set of permissions to the permission object on which it is called,
  461. // returning a new permission object.
  462. func (p Permissions) Grant(n *Permissions) (Permissions, error) {
  463. var out Permissions
  464. var err error
  465. if n == nil {
  466. return p, nil
  467. }
  468. out.KV, err = p.KV.Grant(n.KV)
  469. return out, err
  470. }
  471. // Revoke removes a set of permissions to the permission object on which it is called,
  472. // returning a new permission object.
  473. func (p Permissions) Revoke(n *Permissions) (Permissions, error) {
  474. var out Permissions
  475. var err error
  476. if n == nil {
  477. return p, nil
  478. }
  479. out.KV, err = p.KV.Revoke(n.KV)
  480. return out, err
  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 (rw RWPermission) Grant(n RWPermission) (RWPermission, error) {
  485. var out RWPermission
  486. currentRead := types.NewUnsafeSet(rw.Read...)
  487. for _, r := range n.Read {
  488. if currentRead.Contains(r) {
  489. return out, authErr(http.StatusConflict, "Granting duplicate read permission %s", r)
  490. }
  491. currentRead.Add(r)
  492. }
  493. currentWrite := types.NewUnsafeSet(rw.Write...)
  494. for _, w := range n.Write {
  495. if currentWrite.Contains(w) {
  496. return out, authErr(http.StatusConflict, "Granting duplicate write permission %s", w)
  497. }
  498. currentWrite.Add(w)
  499. }
  500. out.Read = currentRead.Values()
  501. out.Write = currentWrite.Values()
  502. sort.Strings(out.Read)
  503. sort.Strings(out.Write)
  504. return out, nil
  505. }
  506. // Revoke removes a set of permissions to the permission object on which it is called,
  507. // returning a new permission object.
  508. func (rw RWPermission) Revoke(n RWPermission) (RWPermission, error) {
  509. var out RWPermission
  510. currentRead := types.NewUnsafeSet(rw.Read...)
  511. for _, r := range n.Read {
  512. if !currentRead.Contains(r) {
  513. plog.Noticef("revoking ungranted read permission %s", r)
  514. continue
  515. }
  516. currentRead.Remove(r)
  517. }
  518. currentWrite := types.NewUnsafeSet(rw.Write...)
  519. for _, w := range n.Write {
  520. if !currentWrite.Contains(w) {
  521. plog.Noticef("revoking ungranted write permission %s", w)
  522. continue
  523. }
  524. currentWrite.Remove(w)
  525. }
  526. out.Read = currentRead.Values()
  527. out.Write = currentWrite.Values()
  528. sort.Strings(out.Read)
  529. sort.Strings(out.Write)
  530. return out, nil
  531. }
  532. func (rw RWPermission) HasAccess(key string, write bool) bool {
  533. var list []string
  534. if write {
  535. list = rw.Write
  536. } else {
  537. list = rw.Read
  538. }
  539. for _, pat := range list {
  540. match, err := simpleMatch(pat, key)
  541. if err == nil && match {
  542. return true
  543. }
  544. }
  545. return false
  546. }
  547. func (rw RWPermission) HasRecursiveAccess(key string, write bool) bool {
  548. list := rw.Read
  549. if write {
  550. list = rw.Write
  551. }
  552. for _, pat := range list {
  553. match, err := prefixMatch(pat, key)
  554. if err == nil && match {
  555. return true
  556. }
  557. }
  558. return false
  559. }
  560. func simpleMatch(pattern string, key string) (match bool, err error) {
  561. if pattern[len(pattern)-1] == '*' {
  562. return strings.HasPrefix(key, pattern[:len(pattern)-1]), nil
  563. }
  564. return key == pattern, nil
  565. }
  566. func prefixMatch(pattern string, key string) (match bool, err error) {
  567. if pattern[len(pattern)-1] != '*' {
  568. return false, nil
  569. }
  570. return strings.HasPrefix(key, pattern[:len(pattern)-1]), nil
  571. }
  572. func attachRootRole(u User) User {
  573. inRoles := false
  574. for _, r := range u.Roles {
  575. if r == RootRoleName {
  576. inRoles = true
  577. break
  578. }
  579. }
  580. if !inRoles {
  581. u.Roles = append(u.Roles, RootRoleName)
  582. }
  583. return u
  584. }