store.go 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  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. if as.revision == 0 {
  707. as.commitRevision(tx)
  708. }
  709. tx.Unlock()
  710. be.ForceCommit()
  711. return as
  712. }
  713. func hasRootRole(u *authpb.User) bool {
  714. for _, r := range u.Roles {
  715. if r == rootRole {
  716. return true
  717. }
  718. }
  719. return false
  720. }
  721. func (as *authStore) commitRevision(tx backend.BatchTx) {
  722. as.revision++
  723. revBytes := make([]byte, revBytesLen)
  724. binary.BigEndian.PutUint64(revBytes, as.revision)
  725. tx.UnsafePut(authBucketName, revisionKey, revBytes)
  726. }
  727. func getRevision(tx backend.BatchTx) uint64 {
  728. _, vs := tx.UnsafeRange(authBucketName, []byte(revisionKey), nil, 0)
  729. if len(vs) != 1 {
  730. // this can happen in the initialization phase
  731. return 0
  732. }
  733. return binary.BigEndian.Uint64(vs[0])
  734. }
  735. func (as *authStore) Revision() uint64 {
  736. return as.revision
  737. }
  738. func (as *authStore) isValidSimpleToken(token string, ctx context.Context) bool {
  739. splitted := strings.Split(token, ".")
  740. if len(splitted) != 2 {
  741. return false
  742. }
  743. index, err := strconv.Atoi(splitted[1])
  744. if err != nil {
  745. return false
  746. }
  747. select {
  748. case <-as.indexWaiter(uint64(index)):
  749. return true
  750. case <-ctx.Done():
  751. }
  752. return false
  753. }
  754. func (as *authStore) AuthInfoFromTLS(ctx context.Context) *AuthInfo {
  755. peer, ok := peer.FromContext(ctx)
  756. if !ok || peer == nil || peer.AuthInfo == nil {
  757. return nil
  758. }
  759. tlsInfo := peer.AuthInfo.(credentials.TLSInfo)
  760. for _, chains := range tlsInfo.State.VerifiedChains {
  761. for _, chain := range chains {
  762. cn := chain.Subject.CommonName
  763. plog.Debugf("found common name %s", cn)
  764. return &AuthInfo{
  765. Username: cn,
  766. Revision: as.Revision(),
  767. }
  768. }
  769. }
  770. return nil
  771. }
  772. func (as *authStore) AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error) {
  773. md, ok := metadata.FromContext(ctx)
  774. if !ok {
  775. return nil, nil
  776. }
  777. ts, tok := md["token"]
  778. if !tok {
  779. return nil, nil
  780. }
  781. token := ts[0]
  782. if !as.isValidSimpleToken(token, ctx) {
  783. return nil, ErrInvalidAuthToken
  784. }
  785. authInfo, uok := as.AuthInfoFromToken(token)
  786. if !uok {
  787. plog.Warningf("invalid auth token: %s", token)
  788. return nil, ErrInvalidAuthToken
  789. }
  790. return authInfo, nil
  791. }