auth.go 15 KB

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