store.go 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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.FromIncomingContext(ctx)
  767. if !ok {
  768. return nil, nil
  769. }
  770. //TODO(mitake|hexfusion) review unifying key names
  771. ts, ok := md["token"]
  772. if !ok {
  773. ts, ok = md["authorization"]
  774. }
  775. if !ok {
  776. return nil, nil
  777. }
  778. token := ts[0]
  779. authInfo, uok := as.authInfoFromToken(ctx, token)
  780. if !uok {
  781. plog.Warningf("invalid auth token: %s", token)
  782. return nil, ErrInvalidAuthToken
  783. }
  784. return authInfo, nil
  785. }
  786. func (as *authStore) GenTokenPrefix() (string, error) {
  787. return as.tokenProvider.genTokenPrefix()
  788. }
  789. func decomposeOpts(optstr string) (string, map[string]string, error) {
  790. opts := strings.Split(optstr, ",")
  791. tokenType := opts[0]
  792. typeSpecificOpts := make(map[string]string)
  793. for i := 1; i < len(opts); i++ {
  794. pair := strings.Split(opts[i], "=")
  795. if len(pair) != 2 {
  796. plog.Errorf("invalid token specific option: %s", optstr)
  797. return "", nil, ErrInvalidAuthOpts
  798. }
  799. if _, ok := typeSpecificOpts[pair[0]]; ok {
  800. plog.Errorf("invalid token specific option, duplicated parameters (%s): %s", pair[0], optstr)
  801. return "", nil, ErrInvalidAuthOpts
  802. }
  803. typeSpecificOpts[pair[0]] = pair[1]
  804. }
  805. return tokenType, typeSpecificOpts, nil
  806. }
  807. func NewTokenProvider(tokenOpts string, indexWaiter func(uint64) <-chan struct{}) (TokenProvider, error) {
  808. tokenType, typeSpecificOpts, err := decomposeOpts(tokenOpts)
  809. if err != nil {
  810. return nil, ErrInvalidAuthOpts
  811. }
  812. switch tokenType {
  813. case "simple":
  814. plog.Warningf("simple token is not cryptographically signed")
  815. return newTokenProviderSimple(indexWaiter), nil
  816. case "jwt":
  817. return newTokenProviderJWT(typeSpecificOpts)
  818. default:
  819. plog.Errorf("unknown token type: %s", tokenType)
  820. return nil, ErrInvalidAuthOpts
  821. }
  822. }
  823. func (as *authStore) WithRoot(ctx context.Context) context.Context {
  824. if !as.isAuthEnabled() {
  825. return ctx
  826. }
  827. var ctxForAssign context.Context
  828. if ts := as.tokenProvider.(*tokenSimple); ts != nil {
  829. ctx1 := context.WithValue(ctx, "index", uint64(0))
  830. prefix, err := ts.genTokenPrefix()
  831. if err != nil {
  832. plog.Errorf("failed to generate prefix of internally used token")
  833. return ctx
  834. }
  835. ctxForAssign = context.WithValue(ctx1, "simpleToken", prefix)
  836. } else {
  837. ctxForAssign = ctx
  838. }
  839. token, err := as.tokenProvider.assign(ctxForAssign, "root", as.Revision())
  840. if err != nil {
  841. // this must not happen
  842. plog.Errorf("failed to assign token for lease revoking: %s", err)
  843. return ctx
  844. }
  845. mdMap := map[string]string{
  846. "token": token,
  847. }
  848. tokenMD := metadata.New(mdMap)
  849. return metadata.NewContext(ctx, tokenMD)
  850. }