store.go 27 KB

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