store.go 27 KB

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