auth.go 16 KB

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