store.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. // Copyright 2016 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
  15. import (
  16. "bytes"
  17. "encoding/binary"
  18. "errors"
  19. "fmt"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "github.com/coreos/etcd/auth/authpb"
  25. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  26. "github.com/coreos/etcd/mvcc/backend"
  27. "github.com/coreos/pkg/capnslog"
  28. "golang.org/x/crypto/bcrypt"
  29. "golang.org/x/net/context"
  30. "google.golang.org/grpc/metadata"
  31. )
  32. var (
  33. enableFlagKey = []byte("authEnabled")
  34. authEnabled = []byte{1}
  35. authDisabled = []byte{0}
  36. revisionKey = []byte("authRevision")
  37. authBucketName = []byte("auth")
  38. authUsersBucketName = []byte("authUsers")
  39. authRolesBucketName = []byte("authRoles")
  40. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "auth")
  41. ErrRootUserNotExist = errors.New("auth: root user does not exist")
  42. ErrRootRoleNotExist = errors.New("auth: root user does not have root role")
  43. ErrUserAlreadyExist = errors.New("auth: user already exists")
  44. ErrUserEmpty = errors.New("auth: user name is empty")
  45. ErrUserNotFound = errors.New("auth: user not found")
  46. ErrRoleAlreadyExist = errors.New("auth: role already exists")
  47. ErrRoleNotFound = errors.New("auth: role not found")
  48. ErrAuthFailed = errors.New("auth: authentication failed, invalid user ID or password")
  49. ErrPermissionDenied = errors.New("auth: permission denied")
  50. ErrRoleNotGranted = errors.New("auth: role is not granted to the user")
  51. ErrPermissionNotGranted = errors.New("auth: permission is not granted to the role")
  52. ErrAuthNotEnabled = errors.New("auth: authentication is not enabled")
  53. ErrAuthOldRevision = errors.New("auth: revision in header is old")
  54. ErrInvalidAuthToken = errors.New("auth: invalid auth token")
  55. // BcryptCost is the algorithm cost / strength for hashing auth passwords
  56. BcryptCost = bcrypt.DefaultCost
  57. )
  58. const (
  59. rootUser = "root"
  60. rootRole = "root"
  61. revBytesLen = 8
  62. )
  63. type AuthInfo struct {
  64. Username string
  65. Revision uint64
  66. }
  67. type AuthStore interface {
  68. // AuthEnable turns on the authentication feature
  69. AuthEnable() error
  70. // AuthDisable turns off the authentication feature
  71. AuthDisable()
  72. // Authenticate does authentication based on given user name and password
  73. Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error)
  74. // Recover recovers the state of auth store from the given backend
  75. Recover(b backend.Backend)
  76. // UserAdd adds a new user
  77. UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error)
  78. // UserDelete deletes a user
  79. UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error)
  80. // UserChangePassword changes a password of a user
  81. UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error)
  82. // UserGrantRole grants a role to the user
  83. UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error)
  84. // UserGet gets the detailed information of a users
  85. UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error)
  86. // UserRevokeRole revokes a role of a user
  87. UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error)
  88. // RoleAdd adds a new role
  89. RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error)
  90. // RoleGrantPermission grants a permission to a role
  91. RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error)
  92. // RoleGet gets the detailed information of a role
  93. RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error)
  94. // RoleRevokePermission gets the detailed information of a role
  95. RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error)
  96. // RoleDelete gets the detailed information of a role
  97. RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error)
  98. // UserList gets a list of all users
  99. UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error)
  100. // RoleList gets a list of all roles
  101. RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error)
  102. // AuthInfoFromToken gets a username from the given Token and current revision number
  103. // (The revision number is used for preventing the TOCTOU problem)
  104. AuthInfoFromToken(token string) (*AuthInfo, bool)
  105. // IsPutPermitted checks put permission of the user
  106. IsPutPermitted(authInfo *AuthInfo, key []byte) error
  107. // IsRangePermitted checks range permission of the user
  108. IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  109. // IsDeleteRangePermitted checks delete-range permission of the user
  110. IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  111. // IsAdminPermitted checks admin permission of the user
  112. IsAdminPermitted(authInfo *AuthInfo) error
  113. // GenSimpleToken produces a simple random string
  114. GenSimpleToken() (string, error)
  115. // Revision gets current revision of authStore
  116. Revision() uint64
  117. // CheckPassword checks a given pair of username and password is correct
  118. CheckPassword(username, password string) (uint64, error)
  119. // Close does cleanup of AuthStore
  120. Close() error
  121. // AuthInfoFromCtx gets AuthInfo from gRPC's context
  122. AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error)
  123. }
  124. type authStore struct {
  125. be backend.Backend
  126. enabled bool
  127. enabledMu sync.RWMutex
  128. rangePermCache map[string]*unifiedRangePermissions // username -> unifiedRangePermissions
  129. revision uint64
  130. // tokenSimple in v3.2+
  131. indexWaiter func(uint64) <-chan struct{}
  132. simpleTokenKeeper *simpleTokenTTLKeeper
  133. simpleTokensMu sync.Mutex
  134. simpleTokens map[string]string // token -> username
  135. }
  136. func newDeleterFunc(as *authStore) func(string) {
  137. return func(t string) {
  138. as.simpleTokensMu.Lock()
  139. defer as.simpleTokensMu.Unlock()
  140. if username, ok := as.simpleTokens[t]; ok {
  141. plog.Infof("deleting token %s for user %s", t, username)
  142. delete(as.simpleTokens, t)
  143. }
  144. }
  145. }
  146. func (as *authStore) AuthEnable() error {
  147. as.enabledMu.Lock()
  148. defer as.enabledMu.Unlock()
  149. if as.enabled {
  150. plog.Noticef("Authentication already enabled")
  151. return nil
  152. }
  153. b := as.be
  154. tx := b.BatchTx()
  155. tx.Lock()
  156. defer func() {
  157. tx.Unlock()
  158. b.ForceCommit()
  159. }()
  160. u := getUser(tx, rootUser)
  161. if u == nil {
  162. return ErrRootUserNotExist
  163. }
  164. if !hasRootRole(u) {
  165. return ErrRootRoleNotExist
  166. }
  167. tx.UnsafePut(authBucketName, enableFlagKey, authEnabled)
  168. as.enabled = true
  169. as.enable()
  170. as.rangePermCache = make(map[string]*unifiedRangePermissions)
  171. as.revision = getRevision(tx)
  172. plog.Noticef("Authentication enabled")
  173. return nil
  174. }
  175. func (as *authStore) AuthDisable() {
  176. as.enabledMu.Lock()
  177. defer as.enabledMu.Unlock()
  178. if !as.enabled {
  179. return
  180. }
  181. b := as.be
  182. tx := b.BatchTx()
  183. tx.Lock()
  184. tx.UnsafePut(authBucketName, enableFlagKey, authDisabled)
  185. as.commitRevision(tx)
  186. tx.Unlock()
  187. b.ForceCommit()
  188. as.enabled = false
  189. as.simpleTokensMu.Lock()
  190. tk := as.simpleTokenKeeper
  191. as.simpleTokenKeeper = nil
  192. as.simpleTokens = make(map[string]string) // invalidate all tokens
  193. as.simpleTokensMu.Unlock()
  194. if tk != nil {
  195. tk.stop()
  196. }
  197. plog.Noticef("Authentication disabled")
  198. }
  199. func (as *authStore) Close() error {
  200. as.enabledMu.Lock()
  201. defer as.enabledMu.Unlock()
  202. if !as.enabled {
  203. return nil
  204. }
  205. if as.simpleTokenKeeper != nil {
  206. as.simpleTokenKeeper.stop()
  207. as.simpleTokenKeeper = nil
  208. }
  209. return nil
  210. }
  211. func (as *authStore) Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error) {
  212. if !as.isAuthEnabled() {
  213. return nil, ErrAuthNotEnabled
  214. }
  215. // TODO(mitake): after adding jwt support, branching based on values of ctx is required
  216. index := ctx.Value("index").(uint64)
  217. simpleToken := ctx.Value("simpleToken").(string)
  218. tx := as.be.BatchTx()
  219. tx.Lock()
  220. defer tx.Unlock()
  221. user := getUser(tx, username)
  222. if user == nil {
  223. return nil, ErrAuthFailed
  224. }
  225. token := fmt.Sprintf("%s.%d", simpleToken, index)
  226. as.assignSimpleTokenToUser(username, token)
  227. plog.Infof("authorized %s, token is %s", username, token)
  228. return &pb.AuthenticateResponse{Token: token}, nil
  229. }
  230. func (as *authStore) CheckPassword(username, password string) (uint64, error) {
  231. tx := as.be.BatchTx()
  232. tx.Lock()
  233. defer tx.Unlock()
  234. user := getUser(tx, username)
  235. if user == nil {
  236. return 0, ErrAuthFailed
  237. }
  238. if bcrypt.CompareHashAndPassword(user.Password, []byte(password)) != nil {
  239. plog.Noticef("authentication failed, invalid password for user %s", username)
  240. return 0, ErrAuthFailed
  241. }
  242. return getRevision(tx), nil
  243. }
  244. func (as *authStore) Recover(be backend.Backend) {
  245. enabled := false
  246. as.be = be
  247. tx := be.BatchTx()
  248. tx.Lock()
  249. _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0)
  250. if len(vs) == 1 {
  251. if bytes.Equal(vs[0], authEnabled) {
  252. enabled = true
  253. }
  254. }
  255. as.revision = getRevision(tx)
  256. tx.Unlock()
  257. as.enabledMu.Lock()
  258. as.enabled = enabled
  259. as.enabledMu.Unlock()
  260. }
  261. func (as *authStore) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
  262. if len(r.Name) == 0 {
  263. return nil, ErrUserEmpty
  264. }
  265. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), BcryptCost)
  266. if err != nil {
  267. plog.Errorf("failed to hash password: %s", err)
  268. return nil, err
  269. }
  270. tx := as.be.BatchTx()
  271. tx.Lock()
  272. defer tx.Unlock()
  273. user := getUser(tx, r.Name)
  274. if user != nil {
  275. return nil, ErrUserAlreadyExist
  276. }
  277. newUser := &authpb.User{
  278. Name: []byte(r.Name),
  279. Password: hashed,
  280. }
  281. putUser(tx, newUser)
  282. as.commitRevision(tx)
  283. plog.Noticef("added a new user: %s", r.Name)
  284. return &pb.AuthUserAddResponse{}, nil
  285. }
  286. func (as *authStore) UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error) {
  287. tx := as.be.BatchTx()
  288. tx.Lock()
  289. defer tx.Unlock()
  290. user := getUser(tx, r.Name)
  291. if user == nil {
  292. return nil, ErrUserNotFound
  293. }
  294. delUser(tx, r.Name)
  295. as.commitRevision(tx)
  296. as.invalidateCachedPerm(r.Name)
  297. as.invalidateUser(r.Name)
  298. plog.Noticef("deleted a user: %s", r.Name)
  299. return &pb.AuthUserDeleteResponse{}, nil
  300. }
  301. func (as *authStore) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
  302. // TODO(mitake): measure the cost of bcrypt.GenerateFromPassword()
  303. // If the cost is too high, we should move the encryption to outside of the raft
  304. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), BcryptCost)
  305. if err != nil {
  306. plog.Errorf("failed to hash password: %s", err)
  307. return nil, err
  308. }
  309. tx := as.be.BatchTx()
  310. tx.Lock()
  311. defer tx.Unlock()
  312. user := getUser(tx, r.Name)
  313. if user == nil {
  314. return nil, ErrUserNotFound
  315. }
  316. updatedUser := &authpb.User{
  317. Name: []byte(r.Name),
  318. Roles: user.Roles,
  319. Password: hashed,
  320. }
  321. putUser(tx, updatedUser)
  322. as.commitRevision(tx)
  323. as.invalidateCachedPerm(r.Name)
  324. as.invalidateUser(r.Name)
  325. plog.Noticef("changed a password of a user: %s", r.Name)
  326. return &pb.AuthUserChangePasswordResponse{}, nil
  327. }
  328. func (as *authStore) UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error) {
  329. tx := as.be.BatchTx()
  330. tx.Lock()
  331. defer tx.Unlock()
  332. user := getUser(tx, r.User)
  333. if user == nil {
  334. return nil, ErrUserNotFound
  335. }
  336. if r.Role != rootRole {
  337. role := getRole(tx, r.Role)
  338. if role == nil {
  339. return nil, ErrRoleNotFound
  340. }
  341. }
  342. idx := sort.SearchStrings(user.Roles, r.Role)
  343. if idx < len(user.Roles) && strings.Compare(user.Roles[idx], r.Role) == 0 {
  344. plog.Warningf("user %s is already granted role %s", r.User, r.Role)
  345. return &pb.AuthUserGrantRoleResponse{}, nil
  346. }
  347. user.Roles = append(user.Roles, r.Role)
  348. sort.Sort(sort.StringSlice(user.Roles))
  349. putUser(tx, user)
  350. as.invalidateCachedPerm(r.User)
  351. as.commitRevision(tx)
  352. plog.Noticef("granted role %s to user %s", r.Role, r.User)
  353. return &pb.AuthUserGrantRoleResponse{}, nil
  354. }
  355. func (as *authStore) UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error) {
  356. tx := as.be.BatchTx()
  357. tx.Lock()
  358. defer tx.Unlock()
  359. var resp pb.AuthUserGetResponse
  360. user := getUser(tx, r.Name)
  361. if user == nil {
  362. return nil, ErrUserNotFound
  363. }
  364. resp.Roles = append(resp.Roles, user.Roles...)
  365. return &resp, nil
  366. }
  367. func (as *authStore) UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error) {
  368. tx := as.be.BatchTx()
  369. tx.Lock()
  370. defer tx.Unlock()
  371. var resp pb.AuthUserListResponse
  372. users := getAllUsers(tx)
  373. for _, u := range users {
  374. resp.Users = append(resp.Users, string(u.Name))
  375. }
  376. return &resp, nil
  377. }
  378. func (as *authStore) UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error) {
  379. tx := as.be.BatchTx()
  380. tx.Lock()
  381. defer tx.Unlock()
  382. user := getUser(tx, r.Name)
  383. if user == nil {
  384. return nil, ErrUserNotFound
  385. }
  386. updatedUser := &authpb.User{
  387. Name: user.Name,
  388. Password: user.Password,
  389. }
  390. for _, role := range user.Roles {
  391. if strings.Compare(role, r.Role) != 0 {
  392. updatedUser.Roles = append(updatedUser.Roles, role)
  393. }
  394. }
  395. if len(updatedUser.Roles) == len(user.Roles) {
  396. return nil, ErrRoleNotGranted
  397. }
  398. putUser(tx, updatedUser)
  399. as.invalidateCachedPerm(r.Name)
  400. as.commitRevision(tx)
  401. plog.Noticef("revoked role %s from user %s", r.Role, r.Name)
  402. return &pb.AuthUserRevokeRoleResponse{}, nil
  403. }
  404. func (as *authStore) RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error) {
  405. tx := as.be.BatchTx()
  406. tx.Lock()
  407. defer tx.Unlock()
  408. var resp pb.AuthRoleGetResponse
  409. role := getRole(tx, r.Role)
  410. if role == nil {
  411. return nil, ErrRoleNotFound
  412. }
  413. resp.Perm = append(resp.Perm, role.KeyPermission...)
  414. return &resp, nil
  415. }
  416. func (as *authStore) RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error) {
  417. tx := as.be.BatchTx()
  418. tx.Lock()
  419. defer tx.Unlock()
  420. var resp pb.AuthRoleListResponse
  421. roles := getAllRoles(tx)
  422. for _, r := range roles {
  423. resp.Roles = append(resp.Roles, string(r.Name))
  424. }
  425. return &resp, nil
  426. }
  427. func (as *authStore) RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error) {
  428. tx := as.be.BatchTx()
  429. tx.Lock()
  430. defer tx.Unlock()
  431. role := getRole(tx, r.Role)
  432. if role == nil {
  433. return nil, ErrRoleNotFound
  434. }
  435. updatedRole := &authpb.Role{
  436. Name: role.Name,
  437. }
  438. for _, perm := range role.KeyPermission {
  439. if !bytes.Equal(perm.Key, []byte(r.Key)) || !bytes.Equal(perm.RangeEnd, []byte(r.RangeEnd)) {
  440. updatedRole.KeyPermission = append(updatedRole.KeyPermission, perm)
  441. }
  442. }
  443. if len(role.KeyPermission) == len(updatedRole.KeyPermission) {
  444. return nil, ErrPermissionNotGranted
  445. }
  446. putRole(tx, updatedRole)
  447. // TODO(mitake): currently single role update invalidates every cache
  448. // It should be optimized.
  449. as.clearCachedPerm()
  450. as.commitRevision(tx)
  451. plog.Noticef("revoked key %s from role %s", r.Key, r.Role)
  452. return &pb.AuthRoleRevokePermissionResponse{}, nil
  453. }
  454. func (as *authStore) RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error) {
  455. // TODO(mitake): current scheme of role deletion allows existing users to have the deleted roles
  456. //
  457. // Assume a case like below:
  458. // create a role r1
  459. // create a user u1 and grant r1 to u1
  460. // delete r1
  461. //
  462. // After this sequence, u1 is still granted the role r1. So if admin create a new role with the name r1,
  463. // the new r1 is automatically granted u1.
  464. // In some cases, it would be confusing. So we need to provide an option for deleting the grant relation
  465. // from all users.
  466. tx := as.be.BatchTx()
  467. tx.Lock()
  468. defer tx.Unlock()
  469. role := getRole(tx, r.Role)
  470. if role == nil {
  471. return nil, ErrRoleNotFound
  472. }
  473. delRole(tx, r.Role)
  474. as.commitRevision(tx)
  475. plog.Noticef("deleted role %s", r.Role)
  476. return &pb.AuthRoleDeleteResponse{}, nil
  477. }
  478. func (as *authStore) RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  479. tx := as.be.BatchTx()
  480. tx.Lock()
  481. defer tx.Unlock()
  482. role := getRole(tx, r.Name)
  483. if role != nil {
  484. return nil, ErrRoleAlreadyExist
  485. }
  486. newRole := &authpb.Role{
  487. Name: []byte(r.Name),
  488. }
  489. putRole(tx, newRole)
  490. as.commitRevision(tx)
  491. plog.Noticef("Role %s is created", r.Name)
  492. return &pb.AuthRoleAddResponse{}, nil
  493. }
  494. func (as *authStore) AuthInfoFromToken(token string) (*AuthInfo, bool) {
  495. // same as '(t *tokenSimple) info' in v3.2+
  496. as.simpleTokensMu.Lock()
  497. username, ok := as.simpleTokens[token]
  498. if ok && as.simpleTokenKeeper != nil {
  499. as.simpleTokenKeeper.resetSimpleToken(token)
  500. }
  501. as.simpleTokensMu.Unlock()
  502. return &AuthInfo{Username: username, Revision: as.revision}, ok
  503. }
  504. type permSlice []*authpb.Permission
  505. func (perms permSlice) Len() int {
  506. return len(perms)
  507. }
  508. func (perms permSlice) Less(i, j int) bool {
  509. return bytes.Compare(perms[i].Key, perms[j].Key) < 0
  510. }
  511. func (perms permSlice) Swap(i, j int) {
  512. perms[i], perms[j] = perms[j], perms[i]
  513. }
  514. func (as *authStore) RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error) {
  515. tx := as.be.BatchTx()
  516. tx.Lock()
  517. defer tx.Unlock()
  518. role := getRole(tx, r.Name)
  519. if role == nil {
  520. return nil, ErrRoleNotFound
  521. }
  522. idx := sort.Search(len(role.KeyPermission), func(i int) bool {
  523. return bytes.Compare(role.KeyPermission[i].Key, []byte(r.Perm.Key)) >= 0
  524. })
  525. if idx < len(role.KeyPermission) && bytes.Equal(role.KeyPermission[idx].Key, r.Perm.Key) && bytes.Equal(role.KeyPermission[idx].RangeEnd, r.Perm.RangeEnd) {
  526. // update existing permission
  527. role.KeyPermission[idx].PermType = r.Perm.PermType
  528. } else {
  529. // append new permission to the role
  530. newPerm := &authpb.Permission{
  531. Key: []byte(r.Perm.Key),
  532. RangeEnd: []byte(r.Perm.RangeEnd),
  533. PermType: r.Perm.PermType,
  534. }
  535. role.KeyPermission = append(role.KeyPermission, newPerm)
  536. sort.Sort(permSlice(role.KeyPermission))
  537. }
  538. putRole(tx, role)
  539. // TODO(mitake): currently single role update invalidates every cache
  540. // It should be optimized.
  541. as.clearCachedPerm()
  542. as.commitRevision(tx)
  543. plog.Noticef("role %s's permission of key %s is updated as %s", r.Name, r.Perm.Key, authpb.Permission_Type_name[int32(r.Perm.PermType)])
  544. return &pb.AuthRoleGrantPermissionResponse{}, nil
  545. }
  546. func (as *authStore) isOpPermitted(userName string, revision uint64, key, rangeEnd []byte, permTyp authpb.Permission_Type) error {
  547. // TODO(mitake): this function would be costly so we need a caching mechanism
  548. if !as.isAuthEnabled() {
  549. return nil
  550. }
  551. // only gets rev == 0 when passed AuthInfo{}; no user given
  552. if revision == 0 {
  553. return ErrUserEmpty
  554. }
  555. if revision < as.revision {
  556. return ErrAuthOldRevision
  557. }
  558. tx := as.be.BatchTx()
  559. tx.Lock()
  560. defer tx.Unlock()
  561. user := getUser(tx, userName)
  562. if user == nil {
  563. plog.Errorf("invalid user name %s for permission checking", userName)
  564. return ErrPermissionDenied
  565. }
  566. // root role should have permission on all ranges
  567. if hasRootRole(user) {
  568. return nil
  569. }
  570. if as.isRangeOpPermitted(tx, userName, key, rangeEnd, permTyp) {
  571. return nil
  572. }
  573. return ErrPermissionDenied
  574. }
  575. func (as *authStore) IsPutPermitted(authInfo *AuthInfo, key []byte) error {
  576. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, nil, authpb.WRITE)
  577. }
  578. func (as *authStore) IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  579. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.READ)
  580. }
  581. func (as *authStore) IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  582. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.WRITE)
  583. }
  584. func (as *authStore) IsAdminPermitted(authInfo *AuthInfo) error {
  585. if !as.isAuthEnabled() {
  586. return nil
  587. }
  588. if authInfo == nil {
  589. return ErrUserEmpty
  590. }
  591. tx := as.be.BatchTx()
  592. tx.Lock()
  593. defer tx.Unlock()
  594. u := getUser(tx, authInfo.Username)
  595. if u == nil {
  596. return ErrUserNotFound
  597. }
  598. if !hasRootRole(u) {
  599. return ErrPermissionDenied
  600. }
  601. return nil
  602. }
  603. func getUser(tx backend.BatchTx, username string) *authpb.User {
  604. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(username), nil, 0)
  605. if len(vs) == 0 {
  606. return nil
  607. }
  608. user := &authpb.User{}
  609. err := user.Unmarshal(vs[0])
  610. if err != nil {
  611. plog.Panicf("failed to unmarshal user struct (name: %s): %s", username, err)
  612. }
  613. return user
  614. }
  615. func getAllUsers(tx backend.BatchTx) []*authpb.User {
  616. _, vs := tx.UnsafeRange(authUsersBucketName, []byte{0}, []byte{0xff}, -1)
  617. if len(vs) == 0 {
  618. return nil
  619. }
  620. var users []*authpb.User
  621. for _, v := range vs {
  622. user := &authpb.User{}
  623. err := user.Unmarshal(v)
  624. if err != nil {
  625. plog.Panicf("failed to unmarshal user struct: %s", err)
  626. }
  627. users = append(users, user)
  628. }
  629. return users
  630. }
  631. func putUser(tx backend.BatchTx, user *authpb.User) {
  632. b, err := user.Marshal()
  633. if err != nil {
  634. plog.Panicf("failed to marshal user struct (name: %s): %s", user.Name, err)
  635. }
  636. tx.UnsafePut(authUsersBucketName, user.Name, b)
  637. }
  638. func delUser(tx backend.BatchTx, username string) {
  639. tx.UnsafeDelete(authUsersBucketName, []byte(username))
  640. }
  641. func getRole(tx backend.BatchTx, rolename string) *authpb.Role {
  642. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(rolename), nil, 0)
  643. if len(vs) == 0 {
  644. return nil
  645. }
  646. role := &authpb.Role{}
  647. err := role.Unmarshal(vs[0])
  648. if err != nil {
  649. plog.Panicf("failed to unmarshal role struct (name: %s): %s", rolename, err)
  650. }
  651. return role
  652. }
  653. func getAllRoles(tx backend.BatchTx) []*authpb.Role {
  654. _, vs := tx.UnsafeRange(authRolesBucketName, []byte{0}, []byte{0xff}, -1)
  655. if len(vs) == 0 {
  656. return nil
  657. }
  658. var roles []*authpb.Role
  659. for _, v := range vs {
  660. role := &authpb.Role{}
  661. err := role.Unmarshal(v)
  662. if err != nil {
  663. plog.Panicf("failed to unmarshal role struct: %s", err)
  664. }
  665. roles = append(roles, role)
  666. }
  667. return roles
  668. }
  669. func putRole(tx backend.BatchTx, role *authpb.Role) {
  670. b, err := role.Marshal()
  671. if err != nil {
  672. plog.Panicf("failed to marshal role struct (name: %s): %s", role.Name, err)
  673. }
  674. tx.UnsafePut(authRolesBucketName, []byte(role.Name), b)
  675. }
  676. func delRole(tx backend.BatchTx, rolename string) {
  677. tx.UnsafeDelete(authRolesBucketName, []byte(rolename))
  678. }
  679. func (as *authStore) isAuthEnabled() bool {
  680. as.enabledMu.RLock()
  681. defer as.enabledMu.RUnlock()
  682. return as.enabled
  683. }
  684. func NewAuthStore(be backend.Backend, indexWaiter func(uint64) <-chan struct{}) *authStore {
  685. tx := be.BatchTx()
  686. tx.Lock()
  687. tx.UnsafeCreateBucket(authBucketName)
  688. tx.UnsafeCreateBucket(authUsersBucketName)
  689. tx.UnsafeCreateBucket(authRolesBucketName)
  690. enabled := false
  691. _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0)
  692. if len(vs) == 1 {
  693. if bytes.Equal(vs[0], authEnabled) {
  694. enabled = true
  695. }
  696. }
  697. as := &authStore{
  698. be: be,
  699. simpleTokens: make(map[string]string),
  700. revision: getRevision(tx),
  701. indexWaiter: indexWaiter,
  702. enabled: enabled,
  703. rangePermCache: make(map[string]*unifiedRangePermissions),
  704. }
  705. if enabled {
  706. as.enable()
  707. }
  708. if as.revision == 0 {
  709. as.commitRevision(tx)
  710. }
  711. tx.Unlock()
  712. be.ForceCommit()
  713. return as
  714. }
  715. func hasRootRole(u *authpb.User) bool {
  716. for _, r := range u.Roles {
  717. if r == rootRole {
  718. return true
  719. }
  720. }
  721. return false
  722. }
  723. func (as *authStore) commitRevision(tx backend.BatchTx) {
  724. as.revision++
  725. revBytes := make([]byte, revBytesLen)
  726. binary.BigEndian.PutUint64(revBytes, as.revision)
  727. tx.UnsafePut(authBucketName, revisionKey, revBytes)
  728. }
  729. func getRevision(tx backend.BatchTx) uint64 {
  730. _, vs := tx.UnsafeRange(authBucketName, []byte(revisionKey), nil, 0)
  731. if len(vs) != 1 {
  732. // this can happen in the initialization phase
  733. return 0
  734. }
  735. return binary.BigEndian.Uint64(vs[0])
  736. }
  737. func (as *authStore) Revision() uint64 {
  738. return as.revision
  739. }
  740. func (as *authStore) isValidSimpleToken(token string, ctx context.Context) bool {
  741. splitted := strings.Split(token, ".")
  742. if len(splitted) != 2 {
  743. return false
  744. }
  745. index, err := strconv.Atoi(splitted[1])
  746. if err != nil {
  747. return false
  748. }
  749. select {
  750. case <-as.indexWaiter(uint64(index)):
  751. return true
  752. case <-ctx.Done():
  753. }
  754. return false
  755. }
  756. func (as *authStore) AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error) {
  757. md, ok := metadata.FromContext(ctx)
  758. if !ok {
  759. return nil, nil
  760. }
  761. ts, tok := md["token"]
  762. if !tok {
  763. return nil, nil
  764. }
  765. token := ts[0]
  766. if !as.isValidSimpleToken(token, ctx) {
  767. return nil, ErrInvalidAuthToken
  768. }
  769. authInfo, uok := as.AuthInfoFromToken(token)
  770. if !uok {
  771. plog.Warningf("invalid auth token: %s", token)
  772. return nil, ErrInvalidAuthToken
  773. }
  774. return authInfo, nil
  775. }