database_accessor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. package sql
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. "github.com/cloudflare/cfssl/certdb"
  7. cferr "github.com/cloudflare/cfssl/errors"
  8. "github.com/jmoiron/sqlx"
  9. "github.com/kisielk/sqlstruct"
  10. )
  11. // Match to sqlx
  12. func init() {
  13. sqlstruct.TagName = "db"
  14. }
  15. const (
  16. insertSQL = `
  17. INSERT INTO certificates (serial_number, authority_key_identifier, ca_label, status, reason, expiry, revoked_at, pem,
  18. issued_at, not_before, metadata, sans, common_name)
  19. VALUES (:serial_number, :authority_key_identifier, :ca_label, :status, :reason, :expiry, :revoked_at, :pem,
  20. :issued_at, :not_before, :metadata, :sans, :common_name);`
  21. selectSQL = `
  22. SELECT %s FROM certificates
  23. WHERE (serial_number = ? AND authority_key_identifier = ?);`
  24. selectAllUnexpiredSQL = `
  25. SELECT %s FROM certificates
  26. WHERE CURRENT_TIMESTAMP < expiry;`
  27. selectAllRevokedAndUnexpiredWithLabelSQL = `
  28. SELECT %s FROM certificates
  29. WHERE CURRENT_TIMESTAMP < expiry AND status='revoked' AND ca_label= ?;`
  30. selectRevokedAndUnexpiredWithLabelSQL = `
  31. SELECT serial_number, revoked_at FROM certificates
  32. WHERE CURRENT_TIMESTAMP < expiry AND status='revoked' AND ca_label= ?;`
  33. selectAllRevokedAndUnexpiredSQL = `
  34. SELECT %s FROM certificates
  35. WHERE CURRENT_TIMESTAMP < expiry AND status='revoked';`
  36. updateRevokeSQL = `
  37. UPDATE certificates
  38. SET status='revoked', revoked_at=CURRENT_TIMESTAMP, reason=:reason
  39. WHERE (serial_number = :serial_number AND authority_key_identifier = :authority_key_identifier);`
  40. insertOCSPSQL = `
  41. INSERT INTO ocsp_responses (serial_number, authority_key_identifier, body, expiry)
  42. VALUES (:serial_number, :authority_key_identifier, :body, :expiry);`
  43. updateOCSPSQL = `
  44. UPDATE ocsp_responses
  45. SET body = :body, expiry = :expiry
  46. WHERE (serial_number = :serial_number AND authority_key_identifier = :authority_key_identifier);`
  47. selectAllUnexpiredOCSPSQL = `
  48. SELECT %s FROM ocsp_responses
  49. WHERE CURRENT_TIMESTAMP < expiry;`
  50. selectOCSPSQL = `
  51. SELECT %s FROM ocsp_responses
  52. WHERE (serial_number = ? AND authority_key_identifier = ?);`
  53. )
  54. // Accessor implements certdb.Accessor interface.
  55. type Accessor struct {
  56. db *sqlx.DB
  57. }
  58. var _ certdb.Accessor = &Accessor{}
  59. func wrapSQLError(err error) error {
  60. if err != nil {
  61. return cferr.Wrap(cferr.CertStoreError, cferr.Unknown, err)
  62. }
  63. return nil
  64. }
  65. func (d *Accessor) checkDB() error {
  66. if d.db == nil {
  67. return cferr.Wrap(cferr.CertStoreError, cferr.Unknown,
  68. errors.New("unknown db object, please check SetDB method"))
  69. }
  70. return nil
  71. }
  72. // NewAccessor returns a new Accessor.
  73. func NewAccessor(db *sqlx.DB) *Accessor {
  74. return &Accessor{db: db}
  75. }
  76. // SetDB changes the underlying sql.DB object Accessor is manipulating.
  77. func (d *Accessor) SetDB(db *sqlx.DB) {
  78. d.db = db
  79. return
  80. }
  81. // InsertCertificate puts a certdb.CertificateRecord into db.
  82. func (d *Accessor) InsertCertificate(cr certdb.CertificateRecord) error {
  83. err := d.checkDB()
  84. if err != nil {
  85. return err
  86. }
  87. var issuedAt, notBefore *time.Time
  88. if cr.IssuedAt != nil {
  89. t := cr.IssuedAt.UTC()
  90. issuedAt = &t
  91. }
  92. if cr.NotBefore != nil {
  93. t := cr.NotBefore.UTC()
  94. notBefore = &t
  95. }
  96. res, err := d.db.NamedExec(insertSQL, &certdb.CertificateRecord{
  97. Serial: cr.Serial,
  98. AKI: cr.AKI,
  99. CALabel: cr.CALabel,
  100. Status: cr.Status,
  101. Reason: cr.Reason,
  102. Expiry: cr.Expiry.UTC(),
  103. RevokedAt: cr.RevokedAt.UTC(),
  104. PEM: cr.PEM,
  105. IssuedAt: issuedAt,
  106. NotBefore: notBefore,
  107. MetadataJSON: cr.MetadataJSON,
  108. SANsJSON: cr.SANsJSON,
  109. CommonName: cr.CommonName,
  110. })
  111. if err != nil {
  112. return wrapSQLError(err)
  113. }
  114. numRowsAffected, err := res.RowsAffected()
  115. if numRowsAffected == 0 {
  116. return cferr.Wrap(cferr.CertStoreError, cferr.InsertionFailed, fmt.Errorf("failed to insert the certificate record"))
  117. }
  118. if numRowsAffected != 1 {
  119. return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected))
  120. }
  121. return err
  122. }
  123. // GetCertificate gets a certdb.CertificateRecord indexed by serial.
  124. func (d *Accessor) GetCertificate(serial, aki string) (crs []certdb.CertificateRecord, err error) {
  125. err = d.checkDB()
  126. if err != nil {
  127. return nil, err
  128. }
  129. err = d.db.Select(&crs, fmt.Sprintf(d.db.Rebind(selectSQL), sqlstruct.Columns(certdb.CertificateRecord{})), serial, aki)
  130. if err != nil {
  131. return nil, wrapSQLError(err)
  132. }
  133. return crs, nil
  134. }
  135. // GetUnexpiredCertificates gets all unexpired certificate from db.
  136. func (d *Accessor) GetUnexpiredCertificates() (crs []certdb.CertificateRecord, err error) {
  137. err = d.checkDB()
  138. if err != nil {
  139. return nil, err
  140. }
  141. err = d.db.Select(&crs, fmt.Sprintf(d.db.Rebind(selectAllUnexpiredSQL), sqlstruct.Columns(certdb.CertificateRecord{})))
  142. if err != nil {
  143. return nil, wrapSQLError(err)
  144. }
  145. return crs, nil
  146. }
  147. // GetUnexpiredCertificatesByLabel gets all unexpired certificate from db that have the provided label.
  148. func (d *Accessor) GetUnexpiredCertificatesByLabel(labels []string) (crs []certdb.CertificateRecord, err error) {
  149. err = d.checkDB()
  150. if err != nil {
  151. return nil, err
  152. }
  153. query, args, err := sqlx.In(
  154. fmt.Sprintf(`SELECT %s FROM certificates WHERE CURRENT_TIMESTAMP < expiry AND ca_label IN (?)`,
  155. sqlstruct.Columns(certdb.CertificateRecord{}),
  156. ), labels)
  157. if err != nil {
  158. return nil, wrapSQLError(err)
  159. }
  160. err = d.db.Select(&crs, d.db.Rebind(query), args...)
  161. if err != nil {
  162. return nil, wrapSQLError(err)
  163. }
  164. return crs, nil
  165. }
  166. // GetRevokedAndUnexpiredCertificates gets all revoked and unexpired certificate from db (for CRLs).
  167. func (d *Accessor) GetRevokedAndUnexpiredCertificates() (crs []certdb.CertificateRecord, err error) {
  168. err = d.checkDB()
  169. if err != nil {
  170. return nil, err
  171. }
  172. err = d.db.Select(&crs, fmt.Sprintf(d.db.Rebind(selectAllRevokedAndUnexpiredSQL), sqlstruct.Columns(certdb.CertificateRecord{})))
  173. if err != nil {
  174. return nil, wrapSQLError(err)
  175. }
  176. return crs, nil
  177. }
  178. // GetRevokedAndUnexpiredCertificatesByLabel gets all revoked and unexpired certificate from db (for CRLs) with specified ca_label.
  179. func (d *Accessor) GetRevokedAndUnexpiredCertificatesByLabel(label string) (crs []certdb.CertificateRecord, err error) {
  180. err = d.checkDB()
  181. if err != nil {
  182. return nil, err
  183. }
  184. err = d.db.Select(&crs, fmt.Sprintf(d.db.Rebind(selectAllRevokedAndUnexpiredWithLabelSQL), sqlstruct.Columns(certdb.CertificateRecord{})), label)
  185. if err != nil {
  186. return nil, wrapSQLError(err)
  187. }
  188. return crs, nil
  189. }
  190. // GetRevokedAndUnexpiredCertificatesSelectColumnsByLabel gets serial_number and revoed_at from all revoked and unexpired certificate from db (for CRLs) with specified ca_label.
  191. func (d *Accessor) GetRevokedAndUnexpiredCertificatesByLabelSelectColumns(label string) (crs []certdb.CertificateRecord, err error) {
  192. err = d.checkDB()
  193. if err != nil {
  194. return nil, err
  195. }
  196. err = d.db.Select(&crs, d.db.Rebind(selectRevokedAndUnexpiredWithLabelSQL), label)
  197. if err != nil {
  198. return nil, wrapSQLError(err)
  199. }
  200. return crs, nil
  201. }
  202. // RevokeCertificate updates a certificate with a given serial number and marks it revoked.
  203. func (d *Accessor) RevokeCertificate(serial, aki string, reasonCode int) error {
  204. err := d.checkDB()
  205. if err != nil {
  206. return err
  207. }
  208. result, err := d.db.NamedExec(updateRevokeSQL, &certdb.CertificateRecord{
  209. AKI: aki,
  210. Reason: reasonCode,
  211. Serial: serial,
  212. })
  213. if err != nil {
  214. return wrapSQLError(err)
  215. }
  216. numRowsAffected, err := result.RowsAffected()
  217. if numRowsAffected == 0 {
  218. return cferr.Wrap(cferr.CertStoreError, cferr.RecordNotFound, fmt.Errorf("failed to revoke the certificate: certificate not found"))
  219. }
  220. if numRowsAffected != 1 {
  221. return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected))
  222. }
  223. return err
  224. }
  225. // InsertOCSP puts a new certdb.OCSPRecord into the db.
  226. func (d *Accessor) InsertOCSP(rr certdb.OCSPRecord) error {
  227. err := d.checkDB()
  228. if err != nil {
  229. return err
  230. }
  231. result, err := d.db.NamedExec(insertOCSPSQL, &certdb.OCSPRecord{
  232. AKI: rr.AKI,
  233. Body: rr.Body,
  234. Expiry: rr.Expiry.UTC(),
  235. Serial: rr.Serial,
  236. })
  237. if err != nil {
  238. return wrapSQLError(err)
  239. }
  240. numRowsAffected, err := result.RowsAffected()
  241. if numRowsAffected == 0 {
  242. return cferr.Wrap(cferr.CertStoreError, cferr.InsertionFailed, fmt.Errorf("failed to insert the OCSP record"))
  243. }
  244. if numRowsAffected != 1 {
  245. return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected))
  246. }
  247. return err
  248. }
  249. // GetOCSP retrieves a certdb.OCSPRecord from db by serial.
  250. func (d *Accessor) GetOCSP(serial, aki string) (ors []certdb.OCSPRecord, err error) {
  251. err = d.checkDB()
  252. if err != nil {
  253. return nil, err
  254. }
  255. err = d.db.Select(&ors, fmt.Sprintf(d.db.Rebind(selectOCSPSQL), sqlstruct.Columns(certdb.OCSPRecord{})), serial, aki)
  256. if err != nil {
  257. return nil, wrapSQLError(err)
  258. }
  259. return ors, nil
  260. }
  261. // GetUnexpiredOCSPs retrieves all unexpired certdb.OCSPRecord from db.
  262. func (d *Accessor) GetUnexpiredOCSPs() (ors []certdb.OCSPRecord, err error) {
  263. err = d.checkDB()
  264. if err != nil {
  265. return nil, err
  266. }
  267. err = d.db.Select(&ors, fmt.Sprintf(d.db.Rebind(selectAllUnexpiredOCSPSQL), sqlstruct.Columns(certdb.OCSPRecord{})))
  268. if err != nil {
  269. return nil, wrapSQLError(err)
  270. }
  271. return ors, nil
  272. }
  273. // UpdateOCSP updates a ocsp response record with a given serial number.
  274. func (d *Accessor) UpdateOCSP(serial, aki, body string, expiry time.Time) error {
  275. err := d.checkDB()
  276. if err != nil {
  277. return err
  278. }
  279. result, err := d.db.NamedExec(updateOCSPSQL, &certdb.OCSPRecord{
  280. AKI: aki,
  281. Body: body,
  282. Expiry: expiry.UTC(),
  283. Serial: serial,
  284. })
  285. if err != nil {
  286. return wrapSQLError(err)
  287. }
  288. numRowsAffected, err := result.RowsAffected()
  289. if numRowsAffected == 0 {
  290. return cferr.Wrap(cferr.CertStoreError, cferr.RecordNotFound, fmt.Errorf("failed to update the OCSP record"))
  291. }
  292. if numRowsAffected != 1 {
  293. return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected))
  294. }
  295. return err
  296. }
  297. // UpsertOCSP update a ocsp response record with a given serial number,
  298. // or insert the record if it doesn't yet exist in the db
  299. // Implementation note:
  300. // We didn't implement 'upsert' with SQL statement and we lost race condition
  301. // prevention provided by underlying DBMS.
  302. // Reasoning:
  303. // 1. it's difficult to support multiple DBMS backends in the same time, the
  304. // SQL syntax differs from one to another.
  305. // 2. we don't need a strict simultaneous consistency between OCSP and certificate
  306. // status. It's OK that a OCSP response still shows 'good' while the
  307. // corresponding certificate is being revoked seconds ago, as long as the OCSP
  308. // response catches up to be eventually consistent (within hours to days).
  309. // Write race condition between OCSP writers on OCSP table is not a problem,
  310. // since we don't have write race condition on Certificate table and OCSP
  311. // writers should periodically use Certificate table to update OCSP table
  312. // to catch up.
  313. func (d *Accessor) UpsertOCSP(serial, aki, body string, expiry time.Time) error {
  314. err := d.checkDB()
  315. if err != nil {
  316. return err
  317. }
  318. result, err := d.db.NamedExec(updateOCSPSQL, &certdb.OCSPRecord{
  319. AKI: aki,
  320. Body: body,
  321. Expiry: expiry.UTC(),
  322. Serial: serial,
  323. })
  324. if err != nil {
  325. return wrapSQLError(err)
  326. }
  327. numRowsAffected, err := result.RowsAffected()
  328. if numRowsAffected == 0 {
  329. return d.InsertOCSP(certdb.OCSPRecord{Serial: serial, AKI: aki, Body: body, Expiry: expiry})
  330. }
  331. if numRowsAffected != 1 {
  332. return wrapSQLError(fmt.Errorf("%d rows are affected, should be 1 row", numRowsAffected))
  333. }
  334. return err
  335. }