store.go 26 KB

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