auth.go 16 KB

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