store.go 26 KB

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