store.go 28 KB

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