database_accessor.go 9.4 KB

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