store.go 28 KB

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