store.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  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/credentials"
  31. "google.golang.org/grpc/metadata"
  32. "google.golang.org/grpc/peer"
  33. )
  34. var (
  35. enableFlagKey = []byte("authEnabled")
  36. authEnabled = []byte{1}
  37. authDisabled = []byte{0}
  38. revisionKey = []byte("authRevision")
  39. authBucketName = []byte("auth")
  40. authUsersBucketName = []byte("authUsers")
  41. authRolesBucketName = []byte("authRoles")
  42. plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "auth")
  43. ErrRootUserNotExist = errors.New("auth: root user does not exist")
  44. ErrRootRoleNotExist = errors.New("auth: root user does not have root role")
  45. ErrUserAlreadyExist = errors.New("auth: user already exists")
  46. ErrUserEmpty = errors.New("auth: user name is empty")
  47. ErrUserNotFound = errors.New("auth: user not found")
  48. ErrRoleAlreadyExist = errors.New("auth: role already exists")
  49. ErrRoleNotFound = errors.New("auth: role not found")
  50. ErrAuthFailed = errors.New("auth: authentication failed, invalid user ID or password")
  51. ErrPermissionDenied = errors.New("auth: permission denied")
  52. ErrRoleNotGranted = errors.New("auth: role is not granted to the user")
  53. ErrPermissionNotGranted = errors.New("auth: permission is not granted to the role")
  54. ErrAuthNotEnabled = errors.New("auth: authentication is not enabled")
  55. ErrAuthOldRevision = errors.New("auth: revision in header is old")
  56. ErrInvalidAuthToken = errors.New("auth: invalid auth token")
  57. // BcryptCost is the algorithm cost / strength for hashing auth passwords
  58. BcryptCost = bcrypt.DefaultCost
  59. )
  60. const (
  61. rootUser = "root"
  62. rootRole = "root"
  63. revBytesLen = 8
  64. )
  65. type AuthInfo struct {
  66. Username string
  67. Revision uint64
  68. }
  69. type AuthStore interface {
  70. // AuthEnable turns on the authentication feature
  71. AuthEnable() error
  72. // AuthDisable turns off the authentication feature
  73. AuthDisable()
  74. // Authenticate does authentication based on given user name and password
  75. Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error)
  76. // Recover recovers the state of auth store from the given backend
  77. Recover(b backend.Backend)
  78. // UserAdd adds a new user
  79. UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error)
  80. // UserDelete deletes a user
  81. UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error)
  82. // UserChangePassword changes a password of a user
  83. UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error)
  84. // UserGrantRole grants a role to the user
  85. UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error)
  86. // UserGet gets the detailed information of a users
  87. UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error)
  88. // UserRevokeRole revokes a role of a user
  89. UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error)
  90. // RoleAdd adds a new role
  91. RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error)
  92. // RoleGrantPermission grants a permission to a role
  93. RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error)
  94. // RoleGet gets the detailed information of a role
  95. RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error)
  96. // RoleRevokePermission gets the detailed information of a role
  97. RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error)
  98. // RoleDelete gets the detailed information of a role
  99. RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error)
  100. // UserList gets a list of all users
  101. UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error)
  102. // RoleList gets a list of all roles
  103. RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error)
  104. // AuthInfoFromToken gets a username from the given Token and current revision number
  105. // (The revision number is used for preventing the TOCTOU problem)
  106. AuthInfoFromToken(token string) (*AuthInfo, bool)
  107. // IsPutPermitted checks put permission of the user
  108. IsPutPermitted(authInfo *AuthInfo, key []byte) error
  109. // IsRangePermitted checks range permission of the user
  110. IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  111. // IsDeleteRangePermitted checks delete-range permission of the user
  112. IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  113. // IsAdminPermitted checks admin permission of the user
  114. IsAdminPermitted(authInfo *AuthInfo) error
  115. // GenSimpleToken produces a simple random string
  116. GenSimpleToken() (string, error)
  117. // Revision gets current revision of authStore
  118. Revision() uint64
  119. // CheckPassword checks a given pair of username and password is correct
  120. CheckPassword(username, password string) (uint64, error)
  121. // Close does cleanup of AuthStore
  122. Close() error
  123. // AuthInfoFromCtx gets AuthInfo from gRPC's context
  124. AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error)
  125. // AuthInfoFromTLS gets AuthInfo from TLS info of gRPC's context
  126. AuthInfoFromTLS(ctx context.Context) *AuthInfo
  127. }
  128. type authStore struct {
  129. be backend.Backend
  130. enabled bool
  131. enabledMu sync.RWMutex
  132. rangePermCache map[string]*unifiedRangePermissions // username -> unifiedRangePermissions
  133. simpleTokensMu sync.RWMutex
  134. simpleTokens map[string]string // token -> username
  135. simpleTokenKeeper *simpleTokenTTLKeeper
  136. revision uint64
  137. indexWaiter func(uint64) <-chan struct{}
  138. }
  139. func (as *authStore) AuthEnable() error {
  140. as.enabledMu.Lock()
  141. defer as.enabledMu.Unlock()
  142. if as.enabled {
  143. plog.Noticef("Authentication already enabled")
  144. return nil
  145. }
  146. b := as.be
  147. tx := b.BatchTx()
  148. tx.Lock()
  149. defer func() {
  150. tx.Unlock()
  151. b.ForceCommit()
  152. }()
  153. u := getUser(tx, rootUser)
  154. if u == nil {
  155. return ErrRootUserNotExist
  156. }
  157. if !hasRootRole(u) {
  158. return ErrRootRoleNotExist
  159. }
  160. tx.UnsafePut(authBucketName, enableFlagKey, authEnabled)
  161. as.enabled = true
  162. tokenDeleteFunc := func(t string) {
  163. as.simpleTokensMu.Lock()
  164. defer as.simpleTokensMu.Unlock()
  165. if username, ok := as.simpleTokens[t]; ok {
  166. plog.Infof("deleting token %s for user %s", t, username)
  167. delete(as.simpleTokens, t)
  168. }
  169. }
  170. as.simpleTokenKeeper = NewSimpleTokenTTLKeeper(tokenDeleteFunc)
  171. as.rangePermCache = make(map[string]*unifiedRangePermissions)
  172. as.revision = getRevision(tx)
  173. plog.Noticef("Authentication enabled")
  174. return nil
  175. }
  176. func (as *authStore) AuthDisable() {
  177. as.enabledMu.Lock()
  178. defer as.enabledMu.Unlock()
  179. if !as.enabled {
  180. return
  181. }
  182. b := as.be
  183. tx := b.BatchTx()
  184. tx.Lock()
  185. tx.UnsafePut(authBucketName, enableFlagKey, authDisabled)
  186. as.commitRevision(tx)
  187. tx.Unlock()
  188. b.ForceCommit()
  189. as.enabled = false
  190. as.simpleTokensMu.Lock()
  191. as.simpleTokens = make(map[string]string) // invalidate all tokens
  192. as.simpleTokensMu.Unlock()
  193. if as.simpleTokenKeeper != nil {
  194. as.simpleTokenKeeper.stop()
  195. as.simpleTokenKeeper = nil
  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. as.simpleTokensMu.RLock()
  496. defer as.simpleTokensMu.RUnlock()
  497. t, ok := as.simpleTokens[token]
  498. if ok {
  499. as.simpleTokenKeeper.resetSimpleToken(token)
  500. }
  501. return &AuthInfo{Username: t, Revision: as.revision}, ok
  502. }
  503. type permSlice []*authpb.Permission
  504. func (perms permSlice) Len() int {
  505. return len(perms)
  506. }
  507. func (perms permSlice) Less(i, j int) bool {
  508. return bytes.Compare(perms[i].Key, perms[j].Key) < 0
  509. }
  510. func (perms permSlice) Swap(i, j int) {
  511. perms[i], perms[j] = perms[j], perms[i]
  512. }
  513. func (as *authStore) RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error) {
  514. tx := as.be.BatchTx()
  515. tx.Lock()
  516. defer tx.Unlock()
  517. role := getRole(tx, r.Name)
  518. if role == nil {
  519. return nil, ErrRoleNotFound
  520. }
  521. idx := sort.Search(len(role.KeyPermission), func(i int) bool {
  522. return bytes.Compare(role.KeyPermission[i].Key, []byte(r.Perm.Key)) >= 0
  523. })
  524. if idx < len(role.KeyPermission) && bytes.Equal(role.KeyPermission[idx].Key, r.Perm.Key) && bytes.Equal(role.KeyPermission[idx].RangeEnd, r.Perm.RangeEnd) {
  525. // update existing permission
  526. role.KeyPermission[idx].PermType = r.Perm.PermType
  527. } else {
  528. // append new permission to the role
  529. newPerm := &authpb.Permission{
  530. Key: []byte(r.Perm.Key),
  531. RangeEnd: []byte(r.Perm.RangeEnd),
  532. PermType: r.Perm.PermType,
  533. }
  534. role.KeyPermission = append(role.KeyPermission, newPerm)
  535. sort.Sort(permSlice(role.KeyPermission))
  536. }
  537. putRole(tx, role)
  538. // TODO(mitake): currently single role update invalidates every cache
  539. // It should be optimized.
  540. as.clearCachedPerm()
  541. as.commitRevision(tx)
  542. 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)])
  543. return &pb.AuthRoleGrantPermissionResponse{}, nil
  544. }
  545. func (as *authStore) isOpPermitted(userName string, revision uint64, key, rangeEnd []byte, permTyp authpb.Permission_Type) error {
  546. // TODO(mitake): this function would be costly so we need a caching mechanism
  547. if !as.isAuthEnabled() {
  548. return nil
  549. }
  550. // only gets rev == 0 when passed AuthInfo{}; no user given
  551. if revision == 0 {
  552. return ErrUserEmpty
  553. }
  554. if revision < as.revision {
  555. return ErrAuthOldRevision
  556. }
  557. tx := as.be.BatchTx()
  558. tx.Lock()
  559. defer tx.Unlock()
  560. user := getUser(tx, userName)
  561. if user == nil {
  562. plog.Errorf("invalid user name %s for permission checking", userName)
  563. return ErrPermissionDenied
  564. }
  565. // root role should have permission on all ranges
  566. if hasRootRole(user) {
  567. return nil
  568. }
  569. if as.isRangeOpPermitted(tx, userName, key, rangeEnd, permTyp) {
  570. return nil
  571. }
  572. return ErrPermissionDenied
  573. }
  574. func (as *authStore) IsPutPermitted(authInfo *AuthInfo, key []byte) error {
  575. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, nil, authpb.WRITE)
  576. }
  577. func (as *authStore) IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  578. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.READ)
  579. }
  580. func (as *authStore) IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  581. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.WRITE)
  582. }
  583. func (as *authStore) IsAdminPermitted(authInfo *AuthInfo) error {
  584. if !as.isAuthEnabled() {
  585. return nil
  586. }
  587. tx := as.be.BatchTx()
  588. tx.Lock()
  589. defer tx.Unlock()
  590. u := getUser(tx, authInfo.Username)
  591. if u == nil {
  592. return ErrUserNotFound
  593. }
  594. if !hasRootRole(u) {
  595. return ErrPermissionDenied
  596. }
  597. return nil
  598. }
  599. func getUser(tx backend.BatchTx, username string) *authpb.User {
  600. _, vs := tx.UnsafeRange(authUsersBucketName, []byte(username), nil, 0)
  601. if len(vs) == 0 {
  602. return nil
  603. }
  604. user := &authpb.User{}
  605. err := user.Unmarshal(vs[0])
  606. if err != nil {
  607. plog.Panicf("failed to unmarshal user struct (name: %s): %s", username, err)
  608. }
  609. return user
  610. }
  611. func getAllUsers(tx backend.BatchTx) []*authpb.User {
  612. _, vs := tx.UnsafeRange(authUsersBucketName, []byte{0}, []byte{0xff}, -1)
  613. if len(vs) == 0 {
  614. return nil
  615. }
  616. var users []*authpb.User
  617. for _, v := range vs {
  618. user := &authpb.User{}
  619. err := user.Unmarshal(v)
  620. if err != nil {
  621. plog.Panicf("failed to unmarshal user struct: %s", err)
  622. }
  623. users = append(users, user)
  624. }
  625. return users
  626. }
  627. func putUser(tx backend.BatchTx, user *authpb.User) {
  628. b, err := user.Marshal()
  629. if err != nil {
  630. plog.Panicf("failed to marshal user struct (name: %s): %s", user.Name, err)
  631. }
  632. tx.UnsafePut(authUsersBucketName, user.Name, b)
  633. }
  634. func delUser(tx backend.BatchTx, username string) {
  635. tx.UnsafeDelete(authUsersBucketName, []byte(username))
  636. }
  637. func getRole(tx backend.BatchTx, rolename string) *authpb.Role {
  638. _, vs := tx.UnsafeRange(authRolesBucketName, []byte(rolename), nil, 0)
  639. if len(vs) == 0 {
  640. return nil
  641. }
  642. role := &authpb.Role{}
  643. err := role.Unmarshal(vs[0])
  644. if err != nil {
  645. plog.Panicf("failed to unmarshal role struct (name: %s): %s", rolename, err)
  646. }
  647. return role
  648. }
  649. func getAllRoles(tx backend.BatchTx) []*authpb.Role {
  650. _, vs := tx.UnsafeRange(authRolesBucketName, []byte{0}, []byte{0xff}, -1)
  651. if len(vs) == 0 {
  652. return nil
  653. }
  654. var roles []*authpb.Role
  655. for _, v := range vs {
  656. role := &authpb.Role{}
  657. err := role.Unmarshal(v)
  658. if err != nil {
  659. plog.Panicf("failed to unmarshal role struct: %s", err)
  660. }
  661. roles = append(roles, role)
  662. }
  663. return roles
  664. }
  665. func putRole(tx backend.BatchTx, role *authpb.Role) {
  666. b, err := role.Marshal()
  667. if err != nil {
  668. plog.Panicf("failed to marshal role struct (name: %s): %s", role.Name, err)
  669. }
  670. tx.UnsafePut(authRolesBucketName, []byte(role.Name), b)
  671. }
  672. func delRole(tx backend.BatchTx, rolename string) {
  673. tx.UnsafeDelete(authRolesBucketName, []byte(rolename))
  674. }
  675. func (as *authStore) isAuthEnabled() bool {
  676. as.enabledMu.RLock()
  677. defer as.enabledMu.RUnlock()
  678. return as.enabled
  679. }
  680. func NewAuthStore(be backend.Backend, indexWaiter func(uint64) <-chan struct{}) *authStore {
  681. tx := be.BatchTx()
  682. tx.Lock()
  683. tx.UnsafeCreateBucket(authBucketName)
  684. tx.UnsafeCreateBucket(authUsersBucketName)
  685. tx.UnsafeCreateBucket(authRolesBucketName)
  686. as := &authStore{
  687. be: be,
  688. simpleTokens: make(map[string]string),
  689. revision: 0,
  690. indexWaiter: indexWaiter,
  691. }
  692. as.commitRevision(tx)
  693. tx.Unlock()
  694. be.ForceCommit()
  695. return as
  696. }
  697. func hasRootRole(u *authpb.User) bool {
  698. for _, r := range u.Roles {
  699. if r == rootRole {
  700. return true
  701. }
  702. }
  703. return false
  704. }
  705. func (as *authStore) commitRevision(tx backend.BatchTx) {
  706. as.revision++
  707. revBytes := make([]byte, revBytesLen)
  708. binary.BigEndian.PutUint64(revBytes, as.revision)
  709. tx.UnsafePut(authBucketName, revisionKey, revBytes)
  710. }
  711. func getRevision(tx backend.BatchTx) uint64 {
  712. _, vs := tx.UnsafeRange(authBucketName, []byte(revisionKey), nil, 0)
  713. if len(vs) != 1 {
  714. plog.Panicf("failed to get the key of auth store revision")
  715. }
  716. return binary.BigEndian.Uint64(vs[0])
  717. }
  718. func (as *authStore) Revision() uint64 {
  719. return as.revision
  720. }
  721. func (as *authStore) isValidSimpleToken(token string, ctx context.Context) bool {
  722. splitted := strings.Split(token, ".")
  723. if len(splitted) != 2 {
  724. return false
  725. }
  726. index, err := strconv.Atoi(splitted[1])
  727. if err != nil {
  728. return false
  729. }
  730. select {
  731. case <-as.indexWaiter(uint64(index)):
  732. return true
  733. case <-ctx.Done():
  734. }
  735. return false
  736. }
  737. func (as *authStore) AuthInfoFromTLS(ctx context.Context) *AuthInfo {
  738. peer, ok := peer.FromContext(ctx)
  739. if !ok || peer == nil || peer.AuthInfo == nil {
  740. return nil
  741. }
  742. tlsInfo := peer.AuthInfo.(credentials.TLSInfo)
  743. for _, chains := range tlsInfo.State.VerifiedChains {
  744. for _, chain := range chains {
  745. cn := chain.Subject.CommonName
  746. plog.Debugf("found common name %s", cn)
  747. return &AuthInfo{
  748. Username: cn,
  749. Revision: as.Revision(),
  750. }
  751. }
  752. }
  753. return nil
  754. }
  755. func (as *authStore) AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error) {
  756. md, ok := metadata.FromContext(ctx)
  757. if !ok {
  758. return nil, nil
  759. }
  760. ts, tok := md["token"]
  761. if !tok {
  762. return nil, nil
  763. }
  764. token := ts[0]
  765. if !as.isValidSimpleToken(token, ctx) {
  766. return nil, ErrInvalidAuthToken
  767. }
  768. authInfo, uok := as.AuthInfoFromToken(token)
  769. if !uok {
  770. plog.Warningf("invalid auth token: %s", token)
  771. return nil, ErrInvalidAuthToken
  772. }
  773. return authInfo, nil
  774. }