store.go 25 KB

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