store.go 25 KB

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