auth.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601
  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. // CreateOrUpdateUser should be only used for creating the new user or when you are not
  157. // sure if it is a create or update. (When only password is passed in, we are not sure
  158. // if it is a update or create)
  159. func (s *Store) CreateOrUpdateUser(user User) (out User, created bool, err error) {
  160. _, err = s.GetUser(user.User)
  161. if err == 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. if role.Role == RootRoleName {
  307. return Role{}, authErr(http.StatusForbidden, "Cannot modify role %s: is root role.", role.Role)
  308. }
  309. old, err := s.GetRole(role.Role)
  310. if err != nil {
  311. if e, ok := err.(*etcderr.Error); ok {
  312. if e.ErrorCode == etcderr.EcodeKeyNotFound {
  313. return role, authErr(http.StatusNotFound, "Role %s doesn't exist.", role.Role)
  314. }
  315. }
  316. return old, err
  317. }
  318. newRole, err := old.merge(role)
  319. if err != nil {
  320. return old, err
  321. }
  322. if reflect.DeepEqual(old, newRole) {
  323. return old, authErr(http.StatusBadRequest, "Role not updated. Use grant/revoke to update the role.")
  324. }
  325. _, err = s.updateResource("/roles/"+role.Role, newRole)
  326. if err == nil {
  327. plog.Noticef("updated role %s", role.Role)
  328. }
  329. return newRole, err
  330. }
  331. func (s *Store) AuthEnabled() bool {
  332. return s.detectAuth()
  333. }
  334. func (s *Store) EnableAuth() error {
  335. if s.AuthEnabled() {
  336. return authErr(http.StatusConflict, "already enabled")
  337. }
  338. _, err := s.GetUser("root")
  339. if err != nil {
  340. return authErr(http.StatusConflict, "No root user available, please create one")
  341. }
  342. _, err = s.GetRole(GuestRoleName)
  343. if err != nil {
  344. plog.Printf("no guest role access found, creating default")
  345. err := s.CreateRole(guestRole)
  346. if err != nil {
  347. plog.Errorf("error creating guest role. aborting auth enable.")
  348. return err
  349. }
  350. }
  351. err = s.enableAuth()
  352. if err == nil {
  353. plog.Noticef("auth: enabled auth")
  354. } else {
  355. plog.Errorf("error enabling auth (%v)", err)
  356. }
  357. return err
  358. }
  359. func (s *Store) DisableAuth() error {
  360. if !s.AuthEnabled() {
  361. return authErr(http.StatusConflict, "already disabled")
  362. }
  363. err := s.disableAuth()
  364. if err == nil {
  365. plog.Noticef("auth: disabled auth")
  366. } else {
  367. plog.Errorf("error disabling auth (%v)", err)
  368. }
  369. return err
  370. }
  371. // merge applies the properties of the passed-in User to the User on which it
  372. // is called and returns a new User with these modifications applied. Think of
  373. // all Users as immutable sets of data. Merge allows you to perform the set
  374. // operations (desired grants and revokes) atomically
  375. func (u User) merge(n User) (User, error) {
  376. var out User
  377. if u.User != n.User {
  378. return out, authErr(http.StatusConflict, "Merging user data with conflicting usernames: %s %s", u.User, n.User)
  379. }
  380. out.User = u.User
  381. if n.Password != "" {
  382. hash, err := bcrypt.GenerateFromPassword([]byte(n.Password), bcrypt.DefaultCost)
  383. if err != nil {
  384. return User{}, err
  385. }
  386. out.Password = string(hash)
  387. } else {
  388. out.Password = u.Password
  389. }
  390. currentRoles := types.NewUnsafeSet(u.Roles...)
  391. for _, g := range n.Grant {
  392. if currentRoles.Contains(g) {
  393. plog.Noticef("granting duplicate role %s for user %s", g, n.User)
  394. return User{}, authErr(http.StatusConflict, fmt.Sprintf("Granting duplicate role %s for user %s", g, n.User))
  395. }
  396. currentRoles.Add(g)
  397. }
  398. for _, r := range n.Revoke {
  399. if !currentRoles.Contains(r) {
  400. plog.Noticef("revoking ungranted role %s for user %s", r, n.User)
  401. return User{}, authErr(http.StatusConflict, fmt.Sprintf("Revoking ungranted role %s for user %s", r, n.User))
  402. }
  403. currentRoles.Remove(r)
  404. }
  405. out.Roles = currentRoles.Values()
  406. return out, nil
  407. }
  408. func (u User) CheckPassword(password string) bool {
  409. err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
  410. return err == nil
  411. }
  412. // merge for a role works the same as User above -- atomic Role application to
  413. // each of the substructures.
  414. func (r Role) merge(n Role) (Role, error) {
  415. var out Role
  416. var err error
  417. if r.Role != n.Role {
  418. return out, authErr(http.StatusConflict, "Merging role with conflicting names: %s %s", r.Role, n.Role)
  419. }
  420. out.Role = r.Role
  421. out.Permissions, err = r.Permissions.Grant(n.Grant)
  422. if err != nil {
  423. return out, err
  424. }
  425. out.Permissions, err = out.Permissions.Revoke(n.Revoke)
  426. if err != nil {
  427. return out, err
  428. }
  429. return out, nil
  430. }
  431. func (r Role) HasKeyAccess(key string, write bool) bool {
  432. if r.Role == RootRoleName {
  433. return true
  434. }
  435. return r.Permissions.KV.HasAccess(key, write)
  436. }
  437. func (r Role) HasRecursiveAccess(key string, write bool) bool {
  438. if r.Role == RootRoleName {
  439. return true
  440. }
  441. return r.Permissions.KV.HasRecursiveAccess(key, write)
  442. }
  443. // Grant adds a set of permissions to the permission object on which it is called,
  444. // returning a new permission object.
  445. func (p Permissions) Grant(n *Permissions) (Permissions, error) {
  446. var out Permissions
  447. var err error
  448. if n == nil {
  449. return p, nil
  450. }
  451. out.KV, err = p.KV.Grant(n.KV)
  452. return out, err
  453. }
  454. // Revoke removes a set of permissions to the permission object on which it is called,
  455. // returning a new permission object.
  456. func (p Permissions) Revoke(n *Permissions) (Permissions, error) {
  457. var out Permissions
  458. var err error
  459. if n == nil {
  460. return p, nil
  461. }
  462. out.KV, err = p.KV.Revoke(n.KV)
  463. return out, err
  464. }
  465. // Grant adds a set of permissions to the permission object on which it is called,
  466. // returning a new permission object.
  467. func (rw rwPermission) Grant(n rwPermission) (rwPermission, error) {
  468. var out rwPermission
  469. currentRead := types.NewUnsafeSet(rw.Read...)
  470. for _, r := range n.Read {
  471. if currentRead.Contains(r) {
  472. return out, authErr(http.StatusConflict, "Granting duplicate read permission %s", r)
  473. }
  474. currentRead.Add(r)
  475. }
  476. currentWrite := types.NewUnsafeSet(rw.Write...)
  477. for _, w := range n.Write {
  478. if currentWrite.Contains(w) {
  479. return out, authErr(http.StatusConflict, "Granting duplicate write permission %s", w)
  480. }
  481. currentWrite.Add(w)
  482. }
  483. out.Read = currentRead.Values()
  484. out.Write = currentWrite.Values()
  485. return out, nil
  486. }
  487. // Revoke removes a set of permissions to the permission object on which it is called,
  488. // returning a new permission object.
  489. func (rw rwPermission) Revoke(n rwPermission) (rwPermission, error) {
  490. var out rwPermission
  491. currentRead := types.NewUnsafeSet(rw.Read...)
  492. for _, r := range n.Read {
  493. if !currentRead.Contains(r) {
  494. plog.Noticef("revoking ungranted read permission %s", r)
  495. continue
  496. }
  497. currentRead.Remove(r)
  498. }
  499. currentWrite := types.NewUnsafeSet(rw.Write...)
  500. for _, w := range n.Write {
  501. if !currentWrite.Contains(w) {
  502. plog.Noticef("revoking ungranted write permission %s", w)
  503. continue
  504. }
  505. currentWrite.Remove(w)
  506. }
  507. out.Read = currentRead.Values()
  508. out.Write = currentWrite.Values()
  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. }