pk-crypto.scm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. ;;; guile-gcrypt --- crypto tooling for guile
  2. ;;; Copyright © 2013, 2014, 2015, 2017, 2019 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2019 Mathieu Othacehe <m.othacehe@gmail.com>
  4. ;;;
  5. ;;; This file is part of guile-gcrypt.
  6. ;;;
  7. ;;; guile-gcrypt is free software; you can redistribute it and/or modify it
  8. ;;; under the terms of the GNU General Public License as published by
  9. ;;; the Free Software Foundation; either version 3 of the License, or
  10. ;;; (at your option) any later version.
  11. ;;;
  12. ;;; guile-gcrypt is distributed in the hope that it will be useful, but
  13. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. ;;; General Public License for more details.
  16. ;;;
  17. ;;; You should have received a copy of the GNU General Public License
  18. ;;; along with guile-gcrypt. If not, see <http://www.gnu.org/licenses/>.
  19. (define-module (gcrypt pk-crypto)
  20. #:use-module (gcrypt base16)
  21. #:use-module (gcrypt common)
  22. #:use-module (system foreign)
  23. #:use-module (rnrs bytevectors)
  24. #:use-module (ice-9 match)
  25. #:use-module (ice-9 rdelim)
  26. #:export (canonical-sexp?
  27. string->canonical-sexp
  28. canonical-sexp->string
  29. read-file-sexp
  30. number->canonical-sexp
  31. canonical-sexp-car
  32. canonical-sexp-cdr
  33. canonical-sexp-nth
  34. canonical-sexp-nth-data
  35. canonical-sexp-length
  36. canonical-sexp-null?
  37. canonical-sexp-list?
  38. bytevector->hash-data
  39. hash-data->bytevector
  40. key-type
  41. sign
  42. verify
  43. generate-key
  44. find-sexp-token
  45. canonical-sexp->sexp
  46. sexp->canonical-sexp)
  47. #:re-export (gcrypt-version))
  48. ;;; Commentary:
  49. ;;;
  50. ;;; Public key cryptographic routines from GNU Libgcrypt.
  51. ;;;;
  52. ;;; Libgcrypt uses "canonical s-expressions" to represent key material,
  53. ;;; parameters, and data. We keep it as an opaque object to map them to
  54. ;;; Scheme s-expressions because (1) Libgcrypt sexps may be stored in secure
  55. ;;; memory, and (2) the read syntax is different.
  56. ;;;
  57. ;;; A 'canonical-sexp->sexp' procedure is provided nevertheless, for use in
  58. ;;; cases where it is safe to move data out of Libgcrypt---e.g., when
  59. ;;; processing ACL entries, public keys, etc.
  60. ;;;
  61. ;;; Canonical sexps were defined by Rivest et al. in the IETF draft at
  62. ;;; <http://people.csail.mit.edu/rivest/Sexp.txt> for the purposes of SPKI
  63. ;;; (see <http://www.ietf.org/rfc/rfc2693.txt>.)
  64. ;;;
  65. ;;; Code:
  66. ;; Libgcrypt "s-expressions".
  67. (define-wrapped-pointer-type <canonical-sexp>
  68. canonical-sexp?
  69. naked-pointer->canonical-sexp
  70. canonical-sexp->pointer
  71. (lambda (obj port)
  72. ;; Don't print OBJ's external representation: we don't want key material
  73. ;; to leak in backtraces and such.
  74. (format port "#<canonical-sexp ~a | ~a>"
  75. (number->string (object-address obj) 16)
  76. (number->string (pointer-address (canonical-sexp->pointer obj))
  77. 16))))
  78. (define finalize-canonical-sexp!
  79. (libgcrypt->pointer "gcry_sexp_release"))
  80. (define-inlinable (pointer->canonical-sexp ptr)
  81. "Return a <canonical-sexp> that wraps PTR."
  82. (let* ((sexp (naked-pointer->canonical-sexp ptr))
  83. (ptr* (canonical-sexp->pointer sexp)))
  84. ;; Did we already have a <canonical-sexp> object for PTR?
  85. (when (equal? ptr ptr*)
  86. ;; No, so we can safely add a finalizer (in Guile 2.0.9
  87. ;; 'set-pointer-finalizer!' *adds* a finalizer rather than replacing the
  88. ;; existing one.)
  89. (set-pointer-finalizer! ptr finalize-canonical-sexp!))
  90. sexp))
  91. (define string->canonical-sexp
  92. (let ((proc (libgcrypt->procedure int
  93. "gcry_sexp_new"
  94. `(* * ,size_t ,int))))
  95. (lambda (str)
  96. "Parse STR and return the corresponding gcrypt s-expression."
  97. ;; When STR comes from 'canonical-sexp->string', it may contain
  98. ;; characters that are really meant to be interpreted as bytes as in a C
  99. ;; 'char *'. Thus, convert STR to ISO-8859-1 so the byte values of the
  100. ;; characters are preserved.
  101. (let* ((sexp (bytevector->pointer (make-bytevector (sizeof '*))))
  102. (err (proc sexp (string->pointer str "ISO-8859-1") 0 1)))
  103. (if (= 0 err)
  104. (pointer->canonical-sexp (dereference-pointer sexp))
  105. (throw 'gcry-error 'string->canonical-sexp err))))))
  106. (define-syntax GCRYSEXP_FMT_ADVANCED
  107. (identifier-syntax 3))
  108. (define canonical-sexp->string
  109. (let ((proc (libgcrypt->procedure size_t
  110. "gcry_sexp_sprint"
  111. `(* ,int * ,size_t))))
  112. (lambda (sexp)
  113. "Return a textual representation of SEXP."
  114. (let loop ((len 1024))
  115. (let* ((buf (bytevector->pointer (make-bytevector len)))
  116. (size (proc (canonical-sexp->pointer sexp)
  117. GCRYSEXP_FMT_ADVANCED buf len)))
  118. (if (zero? size)
  119. (loop (* len 2))
  120. (pointer->string buf size "ISO-8859-1")))))))
  121. (define (read-file-sexp file)
  122. "Return the canonical sexp read from FILE."
  123. (call-with-input-file file
  124. (compose string->canonical-sexp
  125. read-string)))
  126. (define canonical-sexp-car
  127. (let ((proc (libgcrypt->procedure '* "gcry_sexp_car" '(*))))
  128. (lambda (lst)
  129. "Return the first element of LST, an sexp, if that element is a list;
  130. return #f if LST or its first element is not a list (this is different from
  131. the usual Lisp 'car'.)"
  132. (let ((result (proc (canonical-sexp->pointer lst))))
  133. (if (null-pointer? result)
  134. #f
  135. (pointer->canonical-sexp result))))))
  136. (define canonical-sexp-cdr
  137. (let ((proc (libgcrypt->procedure '* "gcry_sexp_cdr" '(*))))
  138. (lambda (lst)
  139. "Return the tail of LST, an sexp, or #f if LST is not a list."
  140. (let ((result (proc (canonical-sexp->pointer lst))))
  141. (if (null-pointer? result)
  142. #f
  143. (pointer->canonical-sexp result))))))
  144. (define canonical-sexp-nth
  145. (let ((proc (libgcrypt->procedure '* "gcry_sexp_nth" `(* ,int))))
  146. (lambda (lst index)
  147. "Return the INDEXth nested element of LST, an s-expression. Return #f
  148. if that element does not exist, or if it's an atom. (Note: this is obviously
  149. different from Scheme's 'list-ref'.)"
  150. (let ((result (proc (canonical-sexp->pointer lst) index)))
  151. (if (null-pointer? result)
  152. #f
  153. (pointer->canonical-sexp result))))))
  154. (define (dereference-size_t p)
  155. "Return the size_t value pointed to by P."
  156. (bytevector-uint-ref (pointer->bytevector p (sizeof size_t))
  157. 0 (native-endianness)
  158. (sizeof size_t)))
  159. (define canonical-sexp-length
  160. (let ((proc (libgcrypt->procedure int "gcry_sexp_length" '(*))))
  161. (lambda (sexp)
  162. "Return the length of SEXP if it's a list (including the empty list);
  163. return zero if SEXP is an atom."
  164. (proc (canonical-sexp->pointer sexp)))))
  165. (define token-string?
  166. (let ((token-cs (char-set-union char-set:digit
  167. char-set:letter
  168. (char-set #\- #\. #\/ #\_
  169. #\: #\* #\+ #\=))))
  170. (lambda (str)
  171. "Return #t if STR is a token as per Section 4.3 of
  172. <http://people.csail.mit.edu/rivest/Sexp.txt>."
  173. (and (not (string-null? str))
  174. (string-every token-cs str)
  175. (not (char-set-contains? char-set:digit (string-ref str 0)))))))
  176. (define canonical-sexp-nth-data
  177. (let ((proc (libgcrypt->procedure '* "gcry_sexp_nth_data" `(* ,int *))))
  178. (lambda (lst index)
  179. "Return as a symbol (for \"sexp tokens\") or a bytevector (for any other
  180. \"octet string\") the INDEXth data element (atom) of LST, an s-expression.
  181. Return #f if that element does not exist, or if it's a list."
  182. (let* ((size* (bytevector->pointer (make-bytevector (sizeof '*))))
  183. (result (proc (canonical-sexp->pointer lst) index size*)))
  184. (if (null-pointer? result)
  185. #f
  186. (let* ((len (dereference-size_t size*))
  187. (str (pointer->string result len "ISO-8859-1")))
  188. ;; The sexp spec speaks of "tokens" and "octet strings".
  189. ;; Sometimes these octet strings are actual strings (text),
  190. ;; sometimes they're bytevectors, and sometimes they're
  191. ;; multi-precision integers (MPIs). Only the application knows.
  192. ;; However, for convenience, we return a symbol when a token is
  193. ;; encountered since tokens are frequent (at least in the 'car'
  194. ;; of each sexp.)
  195. (if (token-string? str)
  196. (string->symbol str) ; an sexp "token"
  197. (bytevector-copy ; application data, textual or binary
  198. (pointer->bytevector result len)))))))))
  199. (define (number->canonical-sexp number)
  200. "Return an s-expression representing NUMBER."
  201. (let ((hex-number
  202. (match (number->string number 16)
  203. ;; Append a 0 if necessary. For whatever reason gcrypt
  204. ;; rejects hex numbers that don't have an even number of
  205. ;; digits.
  206. ((? (lambda (s) (odd? (string-length s))) odd-string)
  207. (string-append "0" odd-string))
  208. (even-str even-str))))
  209. (string->canonical-sexp (string-append "#" hex-number "#"))))
  210. (define* (bytevector->hash-data bv
  211. #:optional
  212. (hash-algo "sha256")
  213. #:key (key-type 'ecc))
  214. "Given BV, a bytevector containing a hash of type HASH-ALGO, return an
  215. s-expression suitable for use as the 'data' argument for 'sign'. KEY-TYPE
  216. must be a symbol: 'dsa, 'ecc, or 'rsa."
  217. (string->canonical-sexp
  218. (format #f "(data (flags ~a) (hash \"~a\" #~a#))"
  219. (case key-type
  220. ((ecc dsa) "rfc6979")
  221. ((rsa) "pkcs1")
  222. (else (error "unknown key type" key-type)))
  223. hash-algo
  224. (bytevector->base16-string bv))))
  225. (define (key-type sexp)
  226. "Return a symbol denoting the type of public or private key represented by
  227. SEXP--e.g., 'rsa', 'ecc'--or #f if SEXP does not denote a valid key."
  228. (case (canonical-sexp-nth-data sexp 0)
  229. ((public-key private-key)
  230. (canonical-sexp-nth-data (canonical-sexp-nth sexp 1) 0))
  231. (else #f)))
  232. (define* (hash-data->bytevector data)
  233. "Return two values: the hash value (a bytevector), and the hash algorithm (a
  234. string) extracted from DATA, an sexp as returned by 'bytevector->hash-data'.
  235. Return #f if DATA does not conform."
  236. (let ((hash (find-sexp-token data 'hash)))
  237. (if hash
  238. (let ((algo (canonical-sexp-nth-data hash 1))
  239. (value (canonical-sexp-nth-data hash 2)))
  240. (values value (symbol->string algo)))
  241. (values #f #f))))
  242. (define sign
  243. (let ((proc (libgcrypt->procedure int "gcry_pk_sign" '(* * *))))
  244. (lambda (data secret-key)
  245. "Sign DATA, a canonical s-expression representing a suitable hash, with
  246. SECRET-KEY (a canonical s-expression whose car is 'private-key'.) Note that
  247. DATA must be a 'data' s-expression, as returned by
  248. 'bytevector->hash-data' (info \"(gcrypt) Cryptographic Functions\")."
  249. (let* ((sig (bytevector->pointer (make-bytevector (sizeof '*))))
  250. (err (proc sig (canonical-sexp->pointer data)
  251. (canonical-sexp->pointer secret-key))))
  252. (if (= 0 err)
  253. (pointer->canonical-sexp (dereference-pointer sig))
  254. (throw 'gcry-error 'sign err))))))
  255. (define verify
  256. (let ((proc (libgcrypt->procedure int "gcry_pk_verify" '(* * *))))
  257. (lambda (signature data public-key)
  258. "Verify that SIGNATURE is a signature of DATA with PUBLIC-KEY, all of
  259. which are gcrypt s-expressions."
  260. (zero? (proc (canonical-sexp->pointer signature)
  261. (canonical-sexp->pointer data)
  262. (canonical-sexp->pointer public-key))))))
  263. (define generate-key
  264. (let ((proc (libgcrypt->procedure int "gcry_pk_genkey" '(* *))))
  265. (lambda (params)
  266. "Return as an s-expression a new key pair for PARAMS. PARAMS must be an
  267. s-expression like: (genkey (rsa (nbits 4:2048)))."
  268. (let* ((key (bytevector->pointer (make-bytevector (sizeof '*))))
  269. (err (proc key (canonical-sexp->pointer params))))
  270. (if (zero? err)
  271. (pointer->canonical-sexp (dereference-pointer key))
  272. (throw 'gcry-error 'generate-key err))))))
  273. (define find-sexp-token
  274. (let ((proc (libgcrypt->procedure '*
  275. "gcry_sexp_find_token"
  276. `(* * ,size_t))))
  277. (lambda (sexp token)
  278. "Find in SEXP the first element whose 'car' is TOKEN and return it;
  279. return #f if not found."
  280. (let* ((token (string->pointer (symbol->string token)))
  281. (res (proc (canonical-sexp->pointer sexp) token 0)))
  282. (if (null-pointer? res)
  283. #f
  284. (pointer->canonical-sexp res))))))
  285. (define-inlinable (canonical-sexp-null? sexp)
  286. "Return #t if SEXP is the empty-list sexp."
  287. (null-pointer? (canonical-sexp->pointer sexp)))
  288. (define (canonical-sexp-list? sexp)
  289. "Return #t if SEXP is a list."
  290. (or (canonical-sexp-null? sexp)
  291. (> (canonical-sexp-length sexp) 0)))
  292. (define (canonical-sexp-fold proc seed sexp)
  293. "Fold PROC (as per SRFI-1) over SEXP, a canonical sexp."
  294. (if (canonical-sexp-list? sexp)
  295. (let ((len (canonical-sexp-length sexp)))
  296. (let loop ((index 0)
  297. (result seed))
  298. (if (= index len)
  299. result
  300. (loop (+ 1 index)
  301. ;; XXX: Call 'nth-data' *before* 'nth' to work around
  302. ;; <https://bugs.g10code.com/gnupg/issue1594>, which
  303. ;; affects 1.6.0 and earlier versions.
  304. (proc (or (canonical-sexp-nth-data sexp index)
  305. (canonical-sexp-nth sexp index))
  306. result)))))
  307. (error "sexp is not a list" sexp)))
  308. (define (canonical-sexp->sexp sexp)
  309. "Return a Scheme sexp corresponding to SEXP. This is particularly useful to
  310. compare sexps (since Libgcrypt does not provide an 'equal?' procedure), or to
  311. use pattern matching."
  312. (if (canonical-sexp-list? sexp)
  313. (reverse
  314. (canonical-sexp-fold (lambda (item result)
  315. (cons (if (canonical-sexp? item)
  316. (canonical-sexp->sexp item)
  317. item)
  318. result))
  319. '()
  320. sexp))
  321. ;; As of Libgcrypt 1.6.0, there's no function to extract the buffer of a
  322. ;; non-list sexp (!), so we first enlist SEXP, then get at its buffer.
  323. (let ((sexp (string->canonical-sexp
  324. (string-append "(" (canonical-sexp->string sexp)
  325. ")"))))
  326. (or (canonical-sexp-nth-data sexp 0)
  327. (canonical-sexp-nth sexp 0)))))
  328. (define (sexp->canonical-sexp sexp)
  329. "Return a canonical sexp equivalent to SEXP, a Scheme sexp as returned by
  330. 'canonical-sexp->sexp'."
  331. ;; XXX: This is inefficient, but the Libgcrypt API doesn't allow us to do
  332. ;; much better.
  333. (string->canonical-sexp
  334. (call-with-output-string
  335. (lambda (port)
  336. (define (write item)
  337. (cond ((list? item)
  338. (display "(" port)
  339. (for-each write item)
  340. (display ")" port))
  341. ((symbol? item)
  342. (format port " ~a" item))
  343. ((bytevector? item)
  344. (format port " #~a#"
  345. (bytevector->base16-string item)))
  346. (else
  347. (error "unsupported sexp item type" item))))
  348. (write sexp)))))
  349. ;;; pk-crypto.scm ends here