store.go 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  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. ErrInvalidAuthMgmt = errors.New("auth: invalid auth management")
  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. // IsPutPermitted checks put permission of the user
  105. IsPutPermitted(authInfo *AuthInfo, key []byte) error
  106. // IsRangePermitted checks range permission of the user
  107. IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  108. // IsDeleteRangePermitted checks delete-range permission of the user
  109. IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error
  110. // IsAdminPermitted checks admin permission of the user
  111. IsAdminPermitted(authInfo *AuthInfo) error
  112. // GenTokenPrefix produces a random string in a case of simple token
  113. // in a case of JWT, it produces an empty string
  114. GenTokenPrefix() (string, error)
  115. // Revision gets current revision of authStore
  116. Revision() uint64
  117. // CheckPassword checks a given pair of username and password is correct
  118. CheckPassword(username, password string) (uint64, error)
  119. // Close does cleanup of AuthStore
  120. Close() error
  121. // AuthInfoFromCtx gets AuthInfo from gRPC's context
  122. AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error)
  123. // AuthInfoFromTLS gets AuthInfo from TLS info of gRPC's context
  124. AuthInfoFromTLS(ctx context.Context) *AuthInfo
  125. }
  126. type TokenProvider interface {
  127. info(ctx context.Context, token string, revision uint64) (*AuthInfo, bool)
  128. assign(ctx context.Context, username string, revision uint64) (string, error)
  129. enable()
  130. disable()
  131. invalidateUser(string)
  132. genTokenPrefix() (string, error)
  133. }
  134. type authStore struct {
  135. be backend.Backend
  136. enabled bool
  137. enabledMu sync.RWMutex
  138. rangePermCache map[string]*unifiedRangePermissions // username -> unifiedRangePermissions
  139. revision uint64
  140. tokenProvider TokenProvider
  141. }
  142. func (as *authStore) AuthEnable() error {
  143. as.enabledMu.Lock()
  144. defer as.enabledMu.Unlock()
  145. if as.enabled {
  146. plog.Noticef("Authentication already enabled")
  147. return nil
  148. }
  149. b := as.be
  150. tx := b.BatchTx()
  151. tx.Lock()
  152. defer func() {
  153. tx.Unlock()
  154. b.ForceCommit()
  155. }()
  156. u := getUser(tx, rootUser)
  157. if u == nil {
  158. return ErrRootUserNotExist
  159. }
  160. if !hasRootRole(u) {
  161. return ErrRootRoleNotExist
  162. }
  163. tx.UnsafePut(authBucketName, enableFlagKey, authEnabled)
  164. as.enabled = true
  165. as.tokenProvider.enable()
  166. as.rangePermCache = make(map[string]*unifiedRangePermissions)
  167. as.revision = getRevision(tx)
  168. plog.Noticef("Authentication enabled")
  169. return nil
  170. }
  171. func (as *authStore) AuthDisable() {
  172. as.enabledMu.Lock()
  173. defer as.enabledMu.Unlock()
  174. if !as.enabled {
  175. return
  176. }
  177. b := as.be
  178. tx := b.BatchTx()
  179. tx.Lock()
  180. tx.UnsafePut(authBucketName, enableFlagKey, authDisabled)
  181. as.commitRevision(tx)
  182. tx.Unlock()
  183. b.ForceCommit()
  184. as.enabled = false
  185. as.tokenProvider.disable()
  186. plog.Noticef("Authentication disabled")
  187. }
  188. func (as *authStore) Close() error {
  189. as.enabledMu.Lock()
  190. defer as.enabledMu.Unlock()
  191. if !as.enabled {
  192. return nil
  193. }
  194. as.tokenProvider.disable()
  195. return nil
  196. }
  197. func (as *authStore) Authenticate(ctx context.Context, username, password string) (*pb.AuthenticateResponse, error) {
  198. if !as.isAuthEnabled() {
  199. return nil, ErrAuthNotEnabled
  200. }
  201. tx := as.be.BatchTx()
  202. tx.Lock()
  203. defer tx.Unlock()
  204. user := getUser(tx, username)
  205. if user == nil {
  206. return nil, ErrAuthFailed
  207. }
  208. // Password checking is already performed in the API layer, so we don't need to check for now.
  209. // Staleness of password can be detected with OCC in the API layer, too.
  210. token, err := as.tokenProvider.assign(ctx, username, as.revision)
  211. if err != nil {
  212. return nil, err
  213. }
  214. plog.Debugf("authorized %s, token is %s", username, token)
  215. return &pb.AuthenticateResponse{Token: token}, nil
  216. }
  217. func (as *authStore) CheckPassword(username, password string) (uint64, error) {
  218. tx := as.be.BatchTx()
  219. tx.Lock()
  220. defer tx.Unlock()
  221. user := getUser(tx, username)
  222. if user == nil {
  223. return 0, ErrAuthFailed
  224. }
  225. if bcrypt.CompareHashAndPassword(user.Password, []byte(password)) != nil {
  226. plog.Noticef("authentication failed, invalid password for user %s", username)
  227. return 0, ErrAuthFailed
  228. }
  229. return getRevision(tx), nil
  230. }
  231. func (as *authStore) Recover(be backend.Backend) {
  232. enabled := false
  233. as.be = be
  234. tx := be.BatchTx()
  235. tx.Lock()
  236. _, vs := tx.UnsafeRange(authBucketName, enableFlagKey, nil, 0)
  237. if len(vs) == 1 {
  238. if bytes.Equal(vs[0], authEnabled) {
  239. enabled = true
  240. }
  241. }
  242. as.revision = getRevision(tx)
  243. tx.Unlock()
  244. as.enabledMu.Lock()
  245. as.enabled = enabled
  246. as.enabledMu.Unlock()
  247. }
  248. func (as *authStore) UserAdd(r *pb.AuthUserAddRequest) (*pb.AuthUserAddResponse, error) {
  249. if len(r.Name) == 0 {
  250. return nil, ErrUserEmpty
  251. }
  252. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), BcryptCost)
  253. if err != nil {
  254. plog.Errorf("failed to hash password: %s", err)
  255. return nil, err
  256. }
  257. tx := as.be.BatchTx()
  258. tx.Lock()
  259. defer tx.Unlock()
  260. user := getUser(tx, r.Name)
  261. if user != nil {
  262. return nil, ErrUserAlreadyExist
  263. }
  264. newUser := &authpb.User{
  265. Name: []byte(r.Name),
  266. Password: hashed,
  267. }
  268. putUser(tx, newUser)
  269. as.commitRevision(tx)
  270. plog.Noticef("added a new user: %s", r.Name)
  271. return &pb.AuthUserAddResponse{}, nil
  272. }
  273. func (as *authStore) UserDelete(r *pb.AuthUserDeleteRequest) (*pb.AuthUserDeleteResponse, error) {
  274. if as.enabled && strings.Compare(r.Name, rootUser) == 0 {
  275. plog.Errorf("the user root must not be deleted")
  276. return nil, ErrInvalidAuthMgmt
  277. }
  278. tx := as.be.BatchTx()
  279. tx.Lock()
  280. defer tx.Unlock()
  281. user := getUser(tx, r.Name)
  282. if user == nil {
  283. return nil, ErrUserNotFound
  284. }
  285. delUser(tx, r.Name)
  286. as.commitRevision(tx)
  287. as.invalidateCachedPerm(r.Name)
  288. as.tokenProvider.invalidateUser(r.Name)
  289. plog.Noticef("deleted a user: %s", r.Name)
  290. return &pb.AuthUserDeleteResponse{}, nil
  291. }
  292. func (as *authStore) UserChangePassword(r *pb.AuthUserChangePasswordRequest) (*pb.AuthUserChangePasswordResponse, error) {
  293. // TODO(mitake): measure the cost of bcrypt.GenerateFromPassword()
  294. // If the cost is too high, we should move the encryption to outside of the raft
  295. hashed, err := bcrypt.GenerateFromPassword([]byte(r.Password), BcryptCost)
  296. if err != nil {
  297. plog.Errorf("failed to hash password: %s", err)
  298. return nil, err
  299. }
  300. tx := as.be.BatchTx()
  301. tx.Lock()
  302. defer tx.Unlock()
  303. user := getUser(tx, r.Name)
  304. if user == nil {
  305. return nil, ErrUserNotFound
  306. }
  307. updatedUser := &authpb.User{
  308. Name: []byte(r.Name),
  309. Roles: user.Roles,
  310. Password: hashed,
  311. }
  312. putUser(tx, updatedUser)
  313. as.commitRevision(tx)
  314. as.invalidateCachedPerm(r.Name)
  315. as.tokenProvider.invalidateUser(r.Name)
  316. plog.Noticef("changed a password of a user: %s", r.Name)
  317. return &pb.AuthUserChangePasswordResponse{}, nil
  318. }
  319. func (as *authStore) UserGrantRole(r *pb.AuthUserGrantRoleRequest) (*pb.AuthUserGrantRoleResponse, error) {
  320. tx := as.be.BatchTx()
  321. tx.Lock()
  322. defer tx.Unlock()
  323. user := getUser(tx, r.User)
  324. if user == nil {
  325. return nil, ErrUserNotFound
  326. }
  327. if r.Role != rootRole {
  328. role := getRole(tx, r.Role)
  329. if role == nil {
  330. return nil, ErrRoleNotFound
  331. }
  332. }
  333. idx := sort.SearchStrings(user.Roles, r.Role)
  334. if idx < len(user.Roles) && strings.Compare(user.Roles[idx], r.Role) == 0 {
  335. plog.Warningf("user %s is already granted role %s", r.User, r.Role)
  336. return &pb.AuthUserGrantRoleResponse{}, nil
  337. }
  338. user.Roles = append(user.Roles, r.Role)
  339. sort.Sort(sort.StringSlice(user.Roles))
  340. putUser(tx, user)
  341. as.invalidateCachedPerm(r.User)
  342. as.commitRevision(tx)
  343. plog.Noticef("granted role %s to user %s", r.Role, r.User)
  344. return &pb.AuthUserGrantRoleResponse{}, nil
  345. }
  346. func (as *authStore) UserGet(r *pb.AuthUserGetRequest) (*pb.AuthUserGetResponse, error) {
  347. tx := as.be.BatchTx()
  348. tx.Lock()
  349. defer tx.Unlock()
  350. var resp pb.AuthUserGetResponse
  351. user := getUser(tx, r.Name)
  352. if user == nil {
  353. return nil, ErrUserNotFound
  354. }
  355. resp.Roles = append(resp.Roles, user.Roles...)
  356. return &resp, nil
  357. }
  358. func (as *authStore) UserList(r *pb.AuthUserListRequest) (*pb.AuthUserListResponse, error) {
  359. tx := as.be.BatchTx()
  360. tx.Lock()
  361. defer tx.Unlock()
  362. var resp pb.AuthUserListResponse
  363. users := getAllUsers(tx)
  364. for _, u := range users {
  365. resp.Users = append(resp.Users, string(u.Name))
  366. }
  367. return &resp, nil
  368. }
  369. func (as *authStore) UserRevokeRole(r *pb.AuthUserRevokeRoleRequest) (*pb.AuthUserRevokeRoleResponse, error) {
  370. if as.enabled && strings.Compare(r.Name, rootUser) == 0 && strings.Compare(r.Role, rootRole) == 0 {
  371. plog.Errorf("the role root must not be revoked from the user root")
  372. return nil, ErrInvalidAuthMgmt
  373. }
  374. tx := as.be.BatchTx()
  375. tx.Lock()
  376. defer tx.Unlock()
  377. user := getUser(tx, r.Name)
  378. if user == nil {
  379. return nil, ErrUserNotFound
  380. }
  381. updatedUser := &authpb.User{
  382. Name: user.Name,
  383. Password: user.Password,
  384. }
  385. for _, role := range user.Roles {
  386. if strings.Compare(role, r.Role) != 0 {
  387. updatedUser.Roles = append(updatedUser.Roles, role)
  388. }
  389. }
  390. if len(updatedUser.Roles) == len(user.Roles) {
  391. return nil, ErrRoleNotGranted
  392. }
  393. putUser(tx, updatedUser)
  394. as.invalidateCachedPerm(r.Name)
  395. as.commitRevision(tx)
  396. plog.Noticef("revoked role %s from user %s", r.Role, r.Name)
  397. return &pb.AuthUserRevokeRoleResponse{}, nil
  398. }
  399. func (as *authStore) RoleGet(r *pb.AuthRoleGetRequest) (*pb.AuthRoleGetResponse, error) {
  400. tx := as.be.BatchTx()
  401. tx.Lock()
  402. defer tx.Unlock()
  403. var resp pb.AuthRoleGetResponse
  404. role := getRole(tx, r.Role)
  405. if role == nil {
  406. return nil, ErrRoleNotFound
  407. }
  408. resp.Perm = append(resp.Perm, role.KeyPermission...)
  409. return &resp, nil
  410. }
  411. func (as *authStore) RoleList(r *pb.AuthRoleListRequest) (*pb.AuthRoleListResponse, error) {
  412. tx := as.be.BatchTx()
  413. tx.Lock()
  414. defer tx.Unlock()
  415. var resp pb.AuthRoleListResponse
  416. roles := getAllRoles(tx)
  417. for _, r := range roles {
  418. resp.Roles = append(resp.Roles, string(r.Name))
  419. }
  420. return &resp, nil
  421. }
  422. func (as *authStore) RoleRevokePermission(r *pb.AuthRoleRevokePermissionRequest) (*pb.AuthRoleRevokePermissionResponse, error) {
  423. tx := as.be.BatchTx()
  424. tx.Lock()
  425. defer tx.Unlock()
  426. role := getRole(tx, r.Role)
  427. if role == nil {
  428. return nil, ErrRoleNotFound
  429. }
  430. updatedRole := &authpb.Role{
  431. Name: role.Name,
  432. }
  433. for _, perm := range role.KeyPermission {
  434. if !bytes.Equal(perm.Key, []byte(r.Key)) || !bytes.Equal(perm.RangeEnd, []byte(r.RangeEnd)) {
  435. updatedRole.KeyPermission = append(updatedRole.KeyPermission, perm)
  436. }
  437. }
  438. if len(role.KeyPermission) == len(updatedRole.KeyPermission) {
  439. return nil, ErrPermissionNotGranted
  440. }
  441. putRole(tx, updatedRole)
  442. // TODO(mitake): currently single role update invalidates every cache
  443. // It should be optimized.
  444. as.clearCachedPerm()
  445. as.commitRevision(tx)
  446. plog.Noticef("revoked key %s from role %s", r.Key, r.Role)
  447. return &pb.AuthRoleRevokePermissionResponse{}, nil
  448. }
  449. func (as *authStore) RoleDelete(r *pb.AuthRoleDeleteRequest) (*pb.AuthRoleDeleteResponse, error) {
  450. if as.enabled && strings.Compare(r.Role, rootRole) == 0 {
  451. plog.Errorf("the role root must not be deleted")
  452. return nil, ErrInvalidAuthMgmt
  453. }
  454. tx := as.be.BatchTx()
  455. tx.Lock()
  456. defer tx.Unlock()
  457. role := getRole(tx, r.Role)
  458. if role == nil {
  459. return nil, ErrRoleNotFound
  460. }
  461. delRole(tx, r.Role)
  462. users := getAllUsers(tx)
  463. for _, user := range users {
  464. updatedUser := &authpb.User{
  465. Name: user.Name,
  466. Password: user.Password,
  467. }
  468. for _, role := range user.Roles {
  469. if strings.Compare(role, r.Role) != 0 {
  470. updatedUser.Roles = append(updatedUser.Roles, role)
  471. }
  472. }
  473. if len(updatedUser.Roles) == len(user.Roles) {
  474. continue
  475. }
  476. putUser(tx, updatedUser)
  477. as.invalidateCachedPerm(string(user.Name))
  478. }
  479. as.commitRevision(tx)
  480. plog.Noticef("deleted role %s", r.Role)
  481. return &pb.AuthRoleDeleteResponse{}, nil
  482. }
  483. func (as *authStore) RoleAdd(r *pb.AuthRoleAddRequest) (*pb.AuthRoleAddResponse, error) {
  484. tx := as.be.BatchTx()
  485. tx.Lock()
  486. defer tx.Unlock()
  487. role := getRole(tx, r.Name)
  488. if role != nil {
  489. return nil, ErrRoleAlreadyExist
  490. }
  491. newRole := &authpb.Role{
  492. Name: []byte(r.Name),
  493. }
  494. putRole(tx, newRole)
  495. as.commitRevision(tx)
  496. plog.Noticef("Role %s is created", r.Name)
  497. return &pb.AuthRoleAddResponse{}, nil
  498. }
  499. func (as *authStore) authInfoFromToken(ctx context.Context, token string) (*AuthInfo, bool) {
  500. return as.tokenProvider.info(ctx, token, as.revision)
  501. }
  502. type permSlice []*authpb.Permission
  503. func (perms permSlice) Len() int {
  504. return len(perms)
  505. }
  506. func (perms permSlice) Less(i, j int) bool {
  507. return bytes.Compare(perms[i].Key, perms[j].Key) < 0
  508. }
  509. func (perms permSlice) Swap(i, j int) {
  510. perms[i], perms[j] = perms[j], perms[i]
  511. }
  512. func (as *authStore) RoleGrantPermission(r *pb.AuthRoleGrantPermissionRequest) (*pb.AuthRoleGrantPermissionResponse, error) {
  513. tx := as.be.BatchTx()
  514. tx.Lock()
  515. defer tx.Unlock()
  516. role := getRole(tx, r.Name)
  517. if role == nil {
  518. return nil, ErrRoleNotFound
  519. }
  520. idx := sort.Search(len(role.KeyPermission), func(i int) bool {
  521. return bytes.Compare(role.KeyPermission[i].Key, []byte(r.Perm.Key)) >= 0
  522. })
  523. if idx < len(role.KeyPermission) && bytes.Equal(role.KeyPermission[idx].Key, r.Perm.Key) && bytes.Equal(role.KeyPermission[idx].RangeEnd, r.Perm.RangeEnd) {
  524. // update existing permission
  525. role.KeyPermission[idx].PermType = r.Perm.PermType
  526. } else {
  527. // append new permission to the role
  528. newPerm := &authpb.Permission{
  529. Key: []byte(r.Perm.Key),
  530. RangeEnd: []byte(r.Perm.RangeEnd),
  531. PermType: r.Perm.PermType,
  532. }
  533. role.KeyPermission = append(role.KeyPermission, newPerm)
  534. sort.Sort(permSlice(role.KeyPermission))
  535. }
  536. putRole(tx, role)
  537. // TODO(mitake): currently single role update invalidates every cache
  538. // It should be optimized.
  539. as.clearCachedPerm()
  540. as.commitRevision(tx)
  541. 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)])
  542. return &pb.AuthRoleGrantPermissionResponse{}, nil
  543. }
  544. func (as *authStore) isOpPermitted(userName string, revision uint64, key, rangeEnd []byte, permTyp authpb.Permission_Type) error {
  545. // TODO(mitake): this function would be costly so we need a caching mechanism
  546. if !as.isAuthEnabled() {
  547. return nil
  548. }
  549. // only gets rev == 0 when passed AuthInfo{}; no user given
  550. if revision == 0 {
  551. return ErrUserEmpty
  552. }
  553. if revision < as.revision {
  554. return ErrAuthOldRevision
  555. }
  556. tx := as.be.BatchTx()
  557. tx.Lock()
  558. defer tx.Unlock()
  559. user := getUser(tx, userName)
  560. if user == nil {
  561. plog.Errorf("invalid user name %s for permission checking", userName)
  562. return ErrPermissionDenied
  563. }
  564. // root role should have permission on all ranges
  565. if hasRootRole(user) {
  566. return nil
  567. }
  568. if as.isRangeOpPermitted(tx, userName, string(key), string(rangeEnd), permTyp) {
  569. return nil
  570. }
  571. return ErrPermissionDenied
  572. }
  573. func (as *authStore) IsPutPermitted(authInfo *AuthInfo, key []byte) error {
  574. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, nil, authpb.WRITE)
  575. }
  576. func (as *authStore) IsRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  577. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.READ)
  578. }
  579. func (as *authStore) IsDeleteRangePermitted(authInfo *AuthInfo, key, rangeEnd []byte) error {
  580. return as.isOpPermitted(authInfo.Username, authInfo.Revision, key, rangeEnd, authpb.WRITE)
  581. }
  582. func (as *authStore) IsAdminPermitted(authInfo *AuthInfo) error {
  583. if !as.isAuthEnabled() {
  584. return nil
  585. }
  586. if authInfo == nil {
  587. return ErrUserEmpty
  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, tp TokenProvider) *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. revision: getRevision(tx),
  698. enabled: enabled,
  699. rangePermCache: make(map[string]*unifiedRangePermissions),
  700. tokenProvider: tp,
  701. }
  702. if enabled {
  703. as.tokenProvider.enable()
  704. }
  705. if as.revision == 0 {
  706. as.commitRevision(tx)
  707. }
  708. tx.Unlock()
  709. be.ForceCommit()
  710. return as
  711. }
  712. func hasRootRole(u *authpb.User) bool {
  713. for _, r := range u.Roles {
  714. if r == rootRole {
  715. return true
  716. }
  717. }
  718. return false
  719. }
  720. func (as *authStore) commitRevision(tx backend.BatchTx) {
  721. as.revision++
  722. revBytes := make([]byte, revBytesLen)
  723. binary.BigEndian.PutUint64(revBytes, as.revision)
  724. tx.UnsafePut(authBucketName, revisionKey, revBytes)
  725. }
  726. func getRevision(tx backend.BatchTx) uint64 {
  727. _, vs := tx.UnsafeRange(authBucketName, []byte(revisionKey), nil, 0)
  728. if len(vs) != 1 {
  729. // this can happen in the initialization phase
  730. return 0
  731. }
  732. return binary.BigEndian.Uint64(vs[0])
  733. }
  734. func (as *authStore) Revision() uint64 {
  735. return as.revision
  736. }
  737. func (as *authStore) AuthInfoFromTLS(ctx context.Context) *AuthInfo {
  738. peer, ok := peer.FromContext(ctx)
  739. if !ok || peer == nil || peer.AuthInfo == nil {
  740. return nil
  741. }
  742. tlsInfo := peer.AuthInfo.(credentials.TLSInfo)
  743. for _, chains := range tlsInfo.State.VerifiedChains {
  744. for _, chain := range chains {
  745. cn := chain.Subject.CommonName
  746. plog.Debugf("found common name %s", cn)
  747. return &AuthInfo{
  748. Username: cn,
  749. Revision: as.Revision(),
  750. }
  751. }
  752. }
  753. return nil
  754. }
  755. func (as *authStore) AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error) {
  756. md, ok := metadata.FromContext(ctx)
  757. if !ok {
  758. return nil, nil
  759. }
  760. ts, tok := md["token"]
  761. if !tok {
  762. return nil, nil
  763. }
  764. token := ts[0]
  765. authInfo, uok := as.authInfoFromToken(ctx, token)
  766. if !uok {
  767. plog.Warningf("invalid auth token: %s", token)
  768. return nil, ErrInvalidAuthToken
  769. }
  770. return authInfo, nil
  771. }
  772. func (as *authStore) GenTokenPrefix() (string, error) {
  773. return as.tokenProvider.genTokenPrefix()
  774. }
  775. func decomposeOpts(optstr string) (string, map[string]string, error) {
  776. opts := strings.Split(optstr, ",")
  777. tokenType := opts[0]
  778. typeSpecificOpts := make(map[string]string)
  779. for i := 1; i < len(opts); i++ {
  780. pair := strings.Split(opts[i], "=")
  781. if len(pair) != 2 {
  782. plog.Errorf("invalid token specific option: %s", optstr)
  783. return "", nil, ErrInvalidAuthOpts
  784. }
  785. if _, ok := typeSpecificOpts[pair[0]]; ok {
  786. plog.Errorf("invalid token specific option, duplicated parameters (%s): %s", pair[0], optstr)
  787. return "", nil, ErrInvalidAuthOpts
  788. }
  789. typeSpecificOpts[pair[0]] = pair[1]
  790. }
  791. return tokenType, typeSpecificOpts, nil
  792. }
  793. func NewTokenProvider(tokenOpts string, indexWaiter func(uint64) <-chan struct{}) (TokenProvider, error) {
  794. tokenType, typeSpecificOpts, err := decomposeOpts(tokenOpts)
  795. if err != nil {
  796. return nil, ErrInvalidAuthOpts
  797. }
  798. switch tokenType {
  799. case "simple":
  800. plog.Warningf("simple token is not cryptographically signed")
  801. return newTokenProviderSimple(indexWaiter), nil
  802. case "jwt":
  803. return newTokenProviderJWT(typeSpecificOpts)
  804. default:
  805. plog.Errorf("unknown token type: %s", tokenType)
  806. return nil, ErrInvalidAuthOpts
  807. }
  808. }