db.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. package db
  2. import (
  3. "crypto/x509"
  4. "encoding/json"
  5. "strconv"
  6. "strings"
  7. "time"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/nosql"
  10. "github.com/smallstep/nosql/database"
  11. "golang.org/x/crypto/ssh"
  12. )
  13. var (
  14. certsTable = []byte("x509_certs")
  15. revokedCertsTable = []byte("revoked_x509_certs")
  16. revokedSSHCertsTable = []byte("revoked_ssh_certs")
  17. usedOTTTable = []byte("used_ott")
  18. sshCertsTable = []byte("ssh_certs")
  19. sshHostsTable = []byte("ssh_hosts")
  20. sshUsersTable = []byte("ssh_users")
  21. sshHostPrincipalsTable = []byte("ssh_host_principals")
  22. )
  23. // ErrAlreadyExists can be returned if the DB attempts to set a key that has
  24. // been previously set.
  25. var ErrAlreadyExists = errors.New("already exists")
  26. // Config represents the JSON attributes used for configuring a step-ca DB.
  27. type Config struct {
  28. Type string `json:"type"`
  29. DataSource string `json:"dataSource"`
  30. ValueDir string `json:"valueDir,omitempty"`
  31. Database string `json:"database,omitempty"`
  32. // BadgerFileLoadingMode can be set to 'FileIO' (instead of the default
  33. // 'MemoryMap') to avoid memory-mapping log files. This can be useful
  34. // in environments with low RAM
  35. BadgerFileLoadingMode string `json:"badgerFileLoadingMode"`
  36. }
  37. // AuthDB is an interface over an Authority DB client that implements a nosql.DB interface.
  38. type AuthDB interface {
  39. IsRevoked(sn string) (bool, error)
  40. IsSSHRevoked(sn string) (bool, error)
  41. Revoke(rci *RevokedCertificateInfo) error
  42. RevokeSSH(rci *RevokedCertificateInfo) error
  43. StoreCertificate(crt *x509.Certificate) error
  44. UseToken(id, tok string) (bool, error)
  45. IsSSHHost(name string) (bool, error)
  46. StoreSSHCertificate(crt *ssh.Certificate) error
  47. GetSSHHostPrincipals() ([]string, error)
  48. Shutdown() error
  49. }
  50. // DB is a wrapper over the nosql.DB interface.
  51. type DB struct {
  52. nosql.DB
  53. isUp bool
  54. }
  55. // New returns a new database client that implements the AuthDB interface.
  56. func New(c *Config) (AuthDB, error) {
  57. if c == nil {
  58. return newSimpleDB(c)
  59. }
  60. opts := []nosql.Option{nosql.WithDatabase(c.Database),
  61. nosql.WithValueDir(c.ValueDir)}
  62. if len(c.BadgerFileLoadingMode) > 0 {
  63. opts = append(opts, nosql.WithBadgerFileLoadingMode(c.BadgerFileLoadingMode))
  64. }
  65. db, err := nosql.New(c.Type, c.DataSource, opts...)
  66. if err != nil {
  67. return nil, errors.Wrapf(err, "Error opening database of Type %s with source %s", c.Type, c.DataSource)
  68. }
  69. tables := [][]byte{
  70. revokedCertsTable, certsTable, usedOTTTable,
  71. sshCertsTable, sshHostsTable, sshHostPrincipalsTable, sshUsersTable,
  72. revokedSSHCertsTable,
  73. }
  74. for _, b := range tables {
  75. if err := db.CreateTable(b); err != nil {
  76. return nil, errors.Wrapf(err, "error creating table %s",
  77. string(b))
  78. }
  79. }
  80. return &DB{db, true}, nil
  81. }
  82. // RevokedCertificateInfo contains information regarding the certificate
  83. // revocation action.
  84. type RevokedCertificateInfo struct {
  85. Serial string
  86. ProvisionerID string
  87. ReasonCode int
  88. Reason string
  89. RevokedAt time.Time
  90. TokenID string
  91. MTLS bool
  92. }
  93. // IsRevoked returns whether or not a certificate with the given identifier
  94. // has been revoked.
  95. // In the case of an X509 Certificate the `id` should be the Serial Number of
  96. // the Certificate.
  97. func (db *DB) IsRevoked(sn string) (bool, error) {
  98. // If the DB is nil then act as pass through.
  99. if db == nil {
  100. return false, nil
  101. }
  102. // If the error is `Not Found` then the certificate has not been revoked.
  103. // Any other error should be propagated to the caller.
  104. if _, err := db.Get(revokedCertsTable, []byte(sn)); err != nil {
  105. if nosql.IsErrNotFound(err) {
  106. return false, nil
  107. }
  108. return false, errors.Wrap(err, "error checking revocation bucket")
  109. }
  110. // This certificate has been revoked.
  111. return true, nil
  112. }
  113. // IsSSHRevoked returns whether or not a certificate with the given identifier
  114. // has been revoked.
  115. // In the case of an X509 Certificate the `id` should be the Serial Number of
  116. // the Certificate.
  117. func (db *DB) IsSSHRevoked(sn string) (bool, error) {
  118. // If the DB is nil then act as pass through.
  119. if db == nil {
  120. return false, nil
  121. }
  122. // If the error is `Not Found` then the certificate has not been revoked.
  123. // Any other error should be propagated to the caller.
  124. if _, err := db.Get(revokedSSHCertsTable, []byte(sn)); err != nil {
  125. if nosql.IsErrNotFound(err) {
  126. return false, nil
  127. }
  128. return false, errors.Wrap(err, "error checking revocation bucket")
  129. }
  130. // This certificate has been revoked.
  131. return true, nil
  132. }
  133. // Revoke adds a certificate to the revocation table.
  134. func (db *DB) Revoke(rci *RevokedCertificateInfo) error {
  135. rcib, err := json.Marshal(rci)
  136. if err != nil {
  137. return errors.Wrap(err, "error marshaling revoked certificate info")
  138. }
  139. _, swapped, err := db.CmpAndSwap(revokedCertsTable, []byte(rci.Serial), nil, rcib)
  140. switch {
  141. case err != nil:
  142. return errors.Wrap(err, "error AuthDB CmpAndSwap")
  143. case !swapped:
  144. return ErrAlreadyExists
  145. default:
  146. return nil
  147. }
  148. }
  149. // RevokeSSH adds a SSH certificate to the revocation table.
  150. func (db *DB) RevokeSSH(rci *RevokedCertificateInfo) error {
  151. rcib, err := json.Marshal(rci)
  152. if err != nil {
  153. return errors.Wrap(err, "error marshaling revoked certificate info")
  154. }
  155. _, swapped, err := db.CmpAndSwap(revokedSSHCertsTable, []byte(rci.Serial), nil, rcib)
  156. switch {
  157. case err != nil:
  158. return errors.Wrap(err, "error AuthDB CmpAndSwap")
  159. case !swapped:
  160. return ErrAlreadyExists
  161. default:
  162. return nil
  163. }
  164. }
  165. // StoreCertificate stores a certificate PEM.
  166. func (db *DB) StoreCertificate(crt *x509.Certificate) error {
  167. if err := db.Set(certsTable, []byte(crt.SerialNumber.String()), crt.Raw); err != nil {
  168. return errors.Wrap(err, "database Set error")
  169. }
  170. return nil
  171. }
  172. // UseToken returns true if we were able to successfully store the token for
  173. // for the first time, false otherwise.
  174. func (db *DB) UseToken(id, tok string) (bool, error) {
  175. _, swapped, err := db.CmpAndSwap(usedOTTTable, []byte(id), nil, []byte(tok))
  176. if err != nil {
  177. return false, errors.Wrapf(err, "error storing used token %s/%s",
  178. string(usedOTTTable), id)
  179. }
  180. return swapped, nil
  181. }
  182. // IsSSHHost returns if a principal is present in the ssh hosts table.
  183. func (db *DB) IsSSHHost(principal string) (bool, error) {
  184. if _, err := db.Get(sshHostsTable, []byte(strings.ToLower(principal))); err != nil {
  185. if database.IsErrNotFound(err) {
  186. return false, nil
  187. }
  188. return false, errors.Wrap(err, "database Get error")
  189. }
  190. return true, nil
  191. }
  192. type sshHostPrincipalData struct {
  193. Serial string
  194. Expiry uint64
  195. }
  196. // StoreSSHCertificate stores an SSH certificate.
  197. func (db *DB) StoreSSHCertificate(crt *ssh.Certificate) error {
  198. serial := strconv.FormatUint(crt.Serial, 10)
  199. tx := new(database.Tx)
  200. tx.Set(sshCertsTable, []byte(serial), crt.Marshal())
  201. if crt.CertType == ssh.HostCert {
  202. for _, p := range crt.ValidPrincipals {
  203. hostPrincipalData, err := json.Marshal(sshHostPrincipalData{
  204. Serial: serial,
  205. Expiry: crt.ValidBefore,
  206. })
  207. if err != nil {
  208. return err
  209. }
  210. tx.Set(sshHostsTable, []byte(strings.ToLower(p)), []byte(serial))
  211. tx.Set(sshHostPrincipalsTable, []byte(strings.ToLower(p)), hostPrincipalData)
  212. }
  213. } else {
  214. for _, p := range crt.ValidPrincipals {
  215. tx.Set(sshUsersTable, []byte(strings.ToLower(p)), []byte(serial))
  216. }
  217. }
  218. if err := db.Update(tx); err != nil {
  219. return errors.Wrap(err, "database Update error")
  220. }
  221. return nil
  222. }
  223. // GetSSHHostPrincipals gets a list of all valid host principals.
  224. func (db *DB) GetSSHHostPrincipals() ([]string, error) {
  225. entries, err := db.List(sshHostPrincipalsTable)
  226. if err != nil {
  227. return nil, err
  228. }
  229. var principals []string
  230. for _, e := range entries {
  231. var data sshHostPrincipalData
  232. if err := json.Unmarshal(e.Value, &data); err != nil {
  233. return nil, err
  234. }
  235. if time.Unix(int64(data.Expiry), 0).After(time.Now()) {
  236. principals = append(principals, string(e.Key))
  237. }
  238. }
  239. return principals, nil
  240. }
  241. // Shutdown sends a shutdown message to the database.
  242. func (db *DB) Shutdown() error {
  243. if db.isUp {
  244. if err := db.Close(); err != nil {
  245. return errors.Wrap(err, "database shutdown error")
  246. }
  247. db.isUp = false
  248. }
  249. return nil
  250. }
  251. // MockAuthDB mocks the AuthDB interface. //
  252. type MockAuthDB struct {
  253. Err error
  254. Ret1 interface{}
  255. MIsRevoked func(string) (bool, error)
  256. MIsSSHRevoked func(string) (bool, error)
  257. MRevoke func(rci *RevokedCertificateInfo) error
  258. MRevokeSSH func(rci *RevokedCertificateInfo) error
  259. MStoreCertificate func(crt *x509.Certificate) error
  260. MUseToken func(id, tok string) (bool, error)
  261. MIsSSHHost func(principal string) (bool, error)
  262. MStoreSSHCertificate func(crt *ssh.Certificate) error
  263. MGetSSHHostPrincipals func() ([]string, error)
  264. MShutdown func() error
  265. }
  266. // IsRevoked mock.
  267. func (m *MockAuthDB) IsRevoked(sn string) (bool, error) {
  268. if m.MIsRevoked != nil {
  269. return m.MIsRevoked(sn)
  270. }
  271. return m.Ret1.(bool), m.Err
  272. }
  273. // IsSSHRevoked mock.
  274. func (m *MockAuthDB) IsSSHRevoked(sn string) (bool, error) {
  275. if m.MIsSSHRevoked != nil {
  276. return m.MIsSSHRevoked(sn)
  277. }
  278. return m.Ret1.(bool), m.Err
  279. }
  280. // UseToken mock.
  281. func (m *MockAuthDB) UseToken(id, tok string) (bool, error) {
  282. if m.MUseToken != nil {
  283. return m.MUseToken(id, tok)
  284. }
  285. if m.Ret1 == nil {
  286. return false, m.Err
  287. }
  288. return m.Ret1.(bool), m.Err
  289. }
  290. // Revoke mock.
  291. func (m *MockAuthDB) Revoke(rci *RevokedCertificateInfo) error {
  292. if m.MRevoke != nil {
  293. return m.MRevoke(rci)
  294. }
  295. return m.Err
  296. }
  297. // RevokeSSH mock.
  298. func (m *MockAuthDB) RevokeSSH(rci *RevokedCertificateInfo) error {
  299. if m.MRevokeSSH != nil {
  300. return m.MRevokeSSH(rci)
  301. }
  302. return m.Err
  303. }
  304. // StoreCertificate mock.
  305. func (m *MockAuthDB) StoreCertificate(crt *x509.Certificate) error {
  306. if m.MStoreCertificate != nil {
  307. return m.MStoreCertificate(crt)
  308. }
  309. return m.Err
  310. }
  311. // IsSSHHost mock.
  312. func (m *MockAuthDB) IsSSHHost(principal string) (bool, error) {
  313. if m.MIsSSHHost != nil {
  314. return m.MIsSSHHost(principal)
  315. }
  316. return m.Ret1.(bool), m.Err
  317. }
  318. // StoreSSHCertificate mock.
  319. func (m *MockAuthDB) StoreSSHCertificate(crt *ssh.Certificate) error {
  320. if m.MStoreSSHCertificate != nil {
  321. return m.MStoreSSHCertificate(crt)
  322. }
  323. return m.Err
  324. }
  325. // GetSSHHostPrincipals mock.
  326. func (m *MockAuthDB) GetSSHHostPrincipals() ([]string, error) {
  327. if m.MGetSSHHostPrincipals != nil {
  328. return m.MGetSSHHostPrincipals()
  329. }
  330. return m.Ret1.([]string), m.Err
  331. }
  332. // Shutdown mock.
  333. func (m *MockAuthDB) Shutdown() error {
  334. if m.MShutdown != nil {
  335. return m.MShutdown()
  336. }
  337. return m.Err
  338. }
  339. // MockNoSQLDB //
  340. type MockNoSQLDB struct {
  341. Err error
  342. Ret1, Ret2 interface{}
  343. MGet func(bucket, key []byte) ([]byte, error)
  344. MSet func(bucket, key, value []byte) error
  345. MOpen func(dataSourceName string, opt ...database.Option) error
  346. MClose func() error
  347. MCreateTable func(bucket []byte) error
  348. MDeleteTable func(bucket []byte) error
  349. MDel func(bucket, key []byte) error
  350. MList func(bucket []byte) ([]*database.Entry, error)
  351. MUpdate func(tx *database.Tx) error
  352. MCmpAndSwap func(bucket, key, old, newval []byte) ([]byte, bool, error)
  353. }
  354. // CmpAndSwap mock
  355. func (m *MockNoSQLDB) CmpAndSwap(bucket, key, old, newval []byte) ([]byte, bool, error) {
  356. if m.MCmpAndSwap != nil {
  357. return m.MCmpAndSwap(bucket, key, old, newval)
  358. }
  359. if m.Ret1 == nil {
  360. return nil, false, m.Err
  361. }
  362. return m.Ret1.([]byte), m.Ret2.(bool), m.Err
  363. }
  364. // Get mock
  365. func (m *MockNoSQLDB) Get(bucket, key []byte) ([]byte, error) {
  366. if m.MGet != nil {
  367. return m.MGet(bucket, key)
  368. }
  369. if m.Ret1 == nil {
  370. return nil, m.Err
  371. }
  372. return m.Ret1.([]byte), m.Err
  373. }
  374. // Set mock
  375. func (m *MockNoSQLDB) Set(bucket, key, value []byte) error {
  376. if m.MSet != nil {
  377. return m.MSet(bucket, key, value)
  378. }
  379. return m.Err
  380. }
  381. // Open mock
  382. func (m *MockNoSQLDB) Open(dataSourceName string, opt ...database.Option) error {
  383. if m.MOpen != nil {
  384. return m.MOpen(dataSourceName, opt...)
  385. }
  386. return m.Err
  387. }
  388. // Close mock
  389. func (m *MockNoSQLDB) Close() error {
  390. if m.MClose != nil {
  391. return m.MClose()
  392. }
  393. return m.Err
  394. }
  395. // CreateTable mock
  396. func (m *MockNoSQLDB) CreateTable(bucket []byte) error {
  397. if m.MCreateTable != nil {
  398. return m.MCreateTable(bucket)
  399. }
  400. return m.Err
  401. }
  402. // DeleteTable mock
  403. func (m *MockNoSQLDB) DeleteTable(bucket []byte) error {
  404. if m.MDeleteTable != nil {
  405. return m.MDeleteTable(bucket)
  406. }
  407. return m.Err
  408. }
  409. // Del mock
  410. func (m *MockNoSQLDB) Del(bucket, key []byte) error {
  411. if m.MDel != nil {
  412. return m.MDel(bucket, key)
  413. }
  414. return m.Err
  415. }
  416. // List mock
  417. func (m *MockNoSQLDB) List(bucket []byte) ([]*database.Entry, error) {
  418. if m.MList != nil {
  419. return m.MList(bucket)
  420. }
  421. return m.Ret1.([]*database.Entry), m.Err
  422. }
  423. // Update mock
  424. func (m *MockNoSQLDB) Update(tx *database.Tx) error {
  425. if m.MUpdate != nil {
  426. return m.MUpdate(tx)
  427. }
  428. return m.Err
  429. }