openssl.nim 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## OpenSSL wrapper. Supports OpenSSL >= 1.1.0 dynamically (as default) or statically linked
  10. ## using `--dynlibOverride:ssl`.
  11. ##
  12. ## `-d:sslVersion=1.2.3` can be used to force an SSL version.
  13. ## This version must be included in the library name.
  14. ## `-d:useOpenssl3` may be set for OpenSSL 3 instead.
  15. ##
  16. ## There is also limited support for OpenSSL 1.0.x which may require `-d:openssl10`.
  17. ##
  18. ## Build and test examples:
  19. ##
  20. ## ```cmd
  21. ## ./bin/nim c -d:ssl -p:. -r tests/stdlib/tssl.nim
  22. ## ./bin/nim c -d:ssl --threads:on -p:. -r tests/stdlib/thttpclient_ssl.nim
  23. ## ./bin/nim c -d:ssl -p:. -r tests/untestable/tssl.nim
  24. ## ./bin/nim c -d:ssl -p:. --dynlibOverride:ssl --passl:-lcrypto --passl:-lssl -r tests/untestable/tssl.nim
  25. ## ./bin/nim r --putenv:NIM_TESTAMENT_REMOTE_NETWORKING:1 -d:ssl -p:testament/lib --threads:on tests/untestable/thttpclient_ssl_remotenetwork.nim
  26. ## ```
  27. # https://www.feistyduck.com/library/openssl-cookbook/online/ch-testing-with-openssl.html
  28. #
  29. from std/strutils import startsWith
  30. when defined(nimPreviewSlimSystem):
  31. import std/syncio
  32. when defined(nimHasStyleChecks):
  33. {.push styleChecks: off.}
  34. const useWinVersion = defined(windows) or defined(nimdoc)
  35. # To force openSSL version use -d:sslVersion=1.2.3
  36. # See: #10281, #10230
  37. # General issue:
  38. # Other dynamic libraries (like libpg) load different openSSL version then what nim loads.
  39. # Having two different openSSL loaded version causes a crash.
  40. # Use this compile time define to force the openSSL version that your other dynamic libraries want.
  41. const sslVersion {.strdefine.}: string = ""
  42. const useOpenssl3* {.booldefine.} = sslVersion.startsWith('3')
  43. when sslVersion != "":
  44. when defined(macosx):
  45. const
  46. DLLSSLName* = "libssl." & sslVersion & ".dylib"
  47. DLLUtilName* = "libcrypto." & sslVersion & ".dylib"
  48. from std/posix import SocketHandle
  49. elif defined(windows):
  50. const
  51. DLLSSLName* = "libssl-" & sslVersion & ".dll"
  52. DLLUtilName* = "libcrypto-" & sslVersion & ".dll"
  53. from std/winlean import SocketHandle
  54. else:
  55. const
  56. DLLSSLName* = "libssl.so." & sslVersion
  57. DLLUtilName* = "libcrypto.so." & sslVersion
  58. from std/posix import SocketHandle
  59. elif useWinVersion:
  60. when defined(openssl10) or defined(nimOldDlls):
  61. when defined(cpu64):
  62. const
  63. DLLSSLName* = "(ssleay32|ssleay64).dll"
  64. DLLUtilName* = "(libeay32|libeay64).dll"
  65. else:
  66. const
  67. DLLSSLName* = "ssleay32.dll"
  68. DLLUtilName* = "libeay32.dll"
  69. elif defined(cpu64):
  70. const
  71. DLLSSLName* = "(libssl-1_1-x64|ssleay64|libssl64).dll"
  72. DLLUtilName* = "(libcrypto-1_1-x64|libeay64).dll"
  73. else:
  74. const
  75. DLLSSLName* = "(libssl-1_1|ssleay32|libssl32).dll"
  76. DLLUtilName* = "(libcrypto-1_1|libeay32).dll"
  77. from std/winlean import SocketHandle
  78. else:
  79. # same list of versions but ordered differently?
  80. when defined(osx):
  81. const versions = "(.3|.1.1|.38|.39|.41|.43|.44|.45|.46|.47|.48|.10|.1.0.2|.1.0.1|.1.0.0|.0.9.9|.0.9.8|)"
  82. else:
  83. const versions = "(.3|.1.1|.1.0.2|.1.0.1|.1.0.0|.0.9.9|.0.9.8|.48|.47|.46|.45|.44|.43|.41|.39|.38|.10|)"
  84. when defined(macosx):
  85. const
  86. DLLSSLName* = "libssl" & versions & ".dylib"
  87. DLLUtilName* = "libcrypto" & versions & ".dylib"
  88. elif defined(genode):
  89. const
  90. DLLSSLName* = "libssl.lib.so"
  91. DLLUtilName* = "libcrypto.lib.so"
  92. else:
  93. const
  94. DLLSSLName* = "libssl.so" & versions
  95. DLLUtilName* = "libcrypto.so" & versions
  96. from std/posix import SocketHandle
  97. import std/dynlib
  98. {.pragma: lcrypto, cdecl, dynlib: DLLUtilName, importc.}
  99. {.pragma: lssl, cdecl, dynlib: DLLSSLName, importc.}
  100. type
  101. SslStruct {.final, pure.} = object
  102. SslPtr* = ptr SslStruct
  103. PSslPtr* = ptr SslPtr
  104. SslCtx* = SslPtr
  105. PSSL_METHOD* = SslPtr
  106. PSTACK* = SslPtr
  107. PX509* = SslPtr
  108. PX509_NAME* = SslPtr
  109. PBIO_METHOD* = SslPtr
  110. BIO* = SslPtr
  111. EVP_PKEY* = SslPtr
  112. PRSA* = SslPtr
  113. PASN1_UTCTIME* = SslPtr
  114. PASN1_cInt* = SslPtr
  115. PPasswdCb* = SslPtr
  116. EVP_MD* = SslPtr
  117. EVP_MD_CTX* = SslPtr
  118. EVP_PKEY_CTX* = SslPtr
  119. ENGINE* = SslPtr
  120. PFunction* = proc () {.cdecl.}
  121. DES_cblock* = array[0..7, int8]
  122. PDES_cblock* = ptr DES_cblock
  123. des_ks_struct*{.final.} = object
  124. ks*: DES_cblock
  125. weak_key*: cint
  126. des_key_schedule* = array[1..16, des_ks_struct]
  127. pem_password_cb* = proc(buf: cstring, size, rwflag: cint, userdata: pointer): cint {.cdecl.}
  128. PaddingType* = enum
  129. RSA_PKCS1_PADDING = 1.cint,
  130. RSA_SSLV23_PADDING = 2.cint,
  131. RSA_NO_PADDING = 3.cint,
  132. RSA_PKCS1_OAEP_PADDING = 4.cint,
  133. RSA_X931_PADDING = 5.cint,
  134. RSA_PKCS1_PSS_PADDING = 6.cint
  135. const
  136. SSL_SENT_SHUTDOWN* = 1
  137. SSL_RECEIVED_SHUTDOWN* = 2
  138. EVP_MAX_MD_SIZE* = 16 + 20
  139. SSL_ERROR_NONE* = 0
  140. SSL_ERROR_SSL* = 1
  141. SSL_ERROR_WANT_READ* = 2
  142. SSL_ERROR_WANT_WRITE* = 3
  143. SSL_ERROR_WANT_X509_LOOKUP* = 4
  144. SSL_ERROR_SYSCALL* = 5 #look at error stack/return value/errno
  145. SSL_ERROR_ZERO_RETURN* = 6
  146. SSL_ERROR_WANT_CONNECT* = 7
  147. SSL_ERROR_WANT_ACCEPT* = 8
  148. SSL_CTRL_NEED_TMP_RSA* = 1
  149. SSL_CTRL_SET_TMP_RSA* = 2
  150. SSL_CTRL_SET_TMP_DH* = 3
  151. SSL_CTRL_SET_TMP_ECDH* = 4
  152. SSL_CTRL_SET_TMP_RSA_CB* = 5
  153. SSL_CTRL_SET_TMP_DH_CB* = 6
  154. SSL_CTRL_SET_TMP_ECDH_CB* = 7
  155. SSL_CTRL_GET_SESSION_REUSED* = 8
  156. SSL_CTRL_GET_CLIENT_CERT_REQUEST* = 9
  157. SSL_CTRL_GET_NUM_RENEGOTIATIONS* = 10
  158. SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS* = 11
  159. SSL_CTRL_GET_TOTAL_RENEGOTIATIONS* = 12
  160. SSL_CTRL_GET_FLAGS* = 13
  161. SSL_CTRL_EXTRA_CHAIN_CERT* = 14
  162. SSL_CTRL_SET_MSG_CALLBACK* = 15
  163. SSL_CTRL_SET_MSG_CALLBACK_ARG* = 16 # only applies to datagram connections
  164. SSL_CTRL_SET_MTU* = 17 # Stats
  165. SSL_CTRL_SESS_NUMBER* = 20
  166. SSL_CTRL_SESS_CONNECT* = 21
  167. SSL_CTRL_SESS_CONNECT_GOOD* = 22
  168. SSL_CTRL_SESS_CONNECT_RENEGOTIATE* = 23
  169. SSL_CTRL_SESS_ACCEPT* = 24
  170. SSL_CTRL_SESS_ACCEPT_GOOD* = 25
  171. SSL_CTRL_SESS_ACCEPT_RENEGOTIATE* = 26
  172. SSL_CTRL_SESS_HIT* = 27
  173. SSL_CTRL_SESS_CB_HIT* = 28
  174. SSL_CTRL_SESS_MISSES* = 29
  175. SSL_CTRL_SESS_TIMEOUTS* = 30
  176. SSL_CTRL_SESS_CACHE_FULL* = 31
  177. SSL_CTRL_OPTIONS* = 32
  178. SSL_CTRL_MODE* = 33
  179. SSL_CTRL_GET_READ_AHEAD* = 40
  180. SSL_CTRL_SET_READ_AHEAD* = 41
  181. SSL_CTRL_SET_SESS_CACHE_SIZE* = 42
  182. SSL_CTRL_GET_SESS_CACHE_SIZE* = 43
  183. SSL_CTRL_SET_SESS_CACHE_MODE* = 44
  184. SSL_CTRL_GET_SESS_CACHE_MODE* = 45
  185. SSL_CTRL_GET_MAX_CERT_LIST* = 50
  186. SSL_CTRL_SET_MAX_CERT_LIST* = 51 #* Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success
  187. # * when just a single record has been written): *
  188. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB = 53
  189. SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG = 54
  190. SSL_CTRL_SET_TLSEXT_HOSTNAME = 55
  191. SSL_CTRL_SET_ECDH_AUTO* = 94
  192. TLSEXT_NAMETYPE_host_name* = 0
  193. SSL_TLSEXT_ERR_OK* = 0
  194. SSL_TLSEXT_ERR_ALERT_WARNING* = 1
  195. SSL_TLSEXT_ERR_ALERT_FATAL* = 2
  196. SSL_TLSEXT_ERR_NOACK* = 3
  197. SSL_MODE_ENABLE_PARTIAL_WRITE* = 1 #* Make it possible to retry SSL_write() with changed buffer location
  198. # * (buffer contents must stay the same!); this is not the default to avoid
  199. # * the misconception that non-blocking SSL_write() behaves like
  200. # * non-blocking write(): *
  201. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER* = 2 #* Never bother the application with retries if the transport
  202. # * is blocking: *
  203. SSL_MODE_AUTO_RETRY* = 4 #* Don't attempt to automatically build certificate chain *
  204. SSL_MODE_NO_AUTO_CHAIN* = 8
  205. SSL_OP_NO_SSLv2* = 0x01000000
  206. SSL_OP_NO_SSLv3* = 0x02000000
  207. SSL_OP_NO_TLSv1* = 0x04000000
  208. SSL_OP_NO_TLSv1_1* = 0x08000000
  209. SSL_OP_ALL* = 0x000FFFFF
  210. SSL_VERIFY_NONE* = 0x00000000
  211. SSL_VERIFY_PEER* = 0x00000001
  212. SSL_ST_CONNECT* = 0x1000
  213. SSL_ST_ACCEPT* = 0x2000
  214. SSL_ST_INIT* = SSL_ST_CONNECT or SSL_ST_ACCEPT
  215. OPENSSL_DES_DECRYPT* = 0
  216. OPENSSL_DES_ENCRYPT* = 1
  217. X509_V_OK* = 0
  218. X509_V_ILLEGAL* = 1
  219. X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT* = 2
  220. X509_V_ERR_UNABLE_TO_GET_CRL* = 3
  221. X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE* = 4
  222. X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE* = 5
  223. X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY* = 6
  224. X509_V_ERR_CERT_SIGNATURE_FAILURE* = 7
  225. X509_V_ERR_CRL_SIGNATURE_FAILURE* = 8
  226. X509_V_ERR_CERT_NOT_YET_VALID* = 9
  227. X509_V_ERR_CERT_HAS_EXPIRED* = 10
  228. X509_V_ERR_CRL_NOT_YET_VALID* = 11
  229. X509_V_ERR_CRL_HAS_EXPIRED* = 12
  230. X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD* = 13
  231. X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD* = 14
  232. X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD* = 15
  233. X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD* = 16
  234. X509_V_ERR_OUT_OF_MEM* = 17
  235. X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT* = 18
  236. X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN* = 19
  237. X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY* = 20
  238. X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE* = 21
  239. X509_V_ERR_CERT_CHAIN_TOO_LONG* = 22
  240. X509_V_ERR_CERT_REVOKED* = 23
  241. X509_V_ERR_INVALID_CA* = 24
  242. X509_V_ERR_PATH_LENGTH_EXCEEDED* = 25
  243. X509_V_ERR_INVALID_PURPOSE* = 26
  244. X509_V_ERR_CERT_UNTRUSTED* = 27
  245. X509_V_ERR_CERT_REJECTED* = 28 #These are 'informational' when looking for issuer cert
  246. X509_V_ERR_SUBJECT_ISSUER_MISMATCH* = 29
  247. X509_V_ERR_AKID_SKID_MISMATCH* = 30
  248. X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH* = 31
  249. X509_V_ERR_KEYUSAGE_NO_CERTSIGN* = 32
  250. X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER* = 33
  251. X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION* = 34 #The application is not happy
  252. X509_V_ERR_APPLICATION_VERIFICATION* = 50
  253. SSL_FILETYPE_ASN1* = 2
  254. SSL_FILETYPE_PEM* = 1
  255. EVP_PKEY_RSA* = 6 # libssl.dll
  256. BIO_C_SET_CONNECT = 100
  257. BIO_C_DO_STATE_MACHINE = 101
  258. BIO_C_GET_SSL = 110
  259. proc TLSv1_method*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.}
  260. # TLS_method(), TLS_server_method(), TLS_client_method() are introduced in 1.1.0
  261. # and support SSLv3, TLSv1, TLSv1.1 and TLSv1.2
  262. # SSLv23_method(), SSLv23_server_method(), SSLv23_client_method() are removed in 1.1.0
  263. const useStaticLink = compileOption("dynlibOverride", "ssl") or defined(noOpenSSLHacks)
  264. when useStaticLink:
  265. # Static linking
  266. when defined(openssl10):
  267. proc SSL_library_init*(): cint {.cdecl, dynlib: DLLSSLName, importc, discardable.}
  268. proc SSL_load_error_strings*() {.cdecl, dynlib: DLLSSLName, importc.}
  269. proc SSLv23_method*(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc.}
  270. proc SSLeay(): culong {.cdecl, dynlib: DLLUtilName, importc.}
  271. proc getOpenSSLVersion*(): culong =
  272. SSLeay()
  273. proc ERR_load_BIO_strings*() {.cdecl, dynlib: DLLUtilName, importc.}
  274. else:
  275. proc OPENSSL_init_ssl*(opts: uint64, settings: uint8): cint {.cdecl, dynlib: DLLSSLName, importc, discardable.}
  276. proc SSL_library_init*(): cint {.discardable.} =
  277. ## Initialize SSL using OPENSSL_init_ssl for OpenSSL >= 1.1.0
  278. return OPENSSL_init_ssl(0.uint64, 0.uint8)
  279. proc TLS_method*(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc.}
  280. proc SSLv23_method*(): PSSL_METHOD =
  281. TLS_method()
  282. proc OpenSSL_version_num(): culong {.cdecl, dynlib: DLLUtilName, importc.}
  283. proc getOpenSSLVersion*(): culong =
  284. ## Return OpenSSL version as unsigned long
  285. OpenSSL_version_num()
  286. proc SSL_load_error_strings*() =
  287. ## Removed from OpenSSL 1.1.0
  288. # This proc prevents breaking existing code calling SslLoadErrorStrings
  289. # Static linking against OpenSSL < 1.1.0 is not supported
  290. discard
  291. proc ERR_load_BIO_strings*() =
  292. discard
  293. when defined(libressl) or defined(openssl10):
  294. proc SSL_state(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName, importc.}
  295. proc SSL_in_init*(ssl: SslPtr): cint {.inline.} =
  296. SSL_state(ssl) and SSL_ST_INIT
  297. else:
  298. proc SSL_in_init*(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName, importc.}
  299. proc SSL_CTX_set_ciphersuites*(ctx: SslCtx, str: cstring): cint {.cdecl, dynlib: DLLSSLName, importc.}
  300. template OpenSSL_add_all_algorithms*() = discard
  301. proc SSLv23_client_method*(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc.}
  302. proc SSLv2_method*(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc.}
  303. proc SSLv3_method*(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc.}
  304. proc CRYPTO_set_mem_functions(a,b,c: pointer){.cdecl, dynlib: DLLUtilName, importc.}
  305. else:
  306. # Here we're trying to stay compatible between openssl versions. Some
  307. # symbols are loaded dynamically and we don't use them if not found.
  308. proc thisModule(): LibHandle {.inline.} =
  309. var thisMod {.global.}: LibHandle
  310. if thisMod.isNil: thisMod = loadLib()
  311. result = thisMod
  312. proc sslModule(): LibHandle {.inline, raises: [LibraryError], tags:[RootEffect].} =
  313. var sslMod {.global.}: LibHandle
  314. try:
  315. if sslMod.isNil: sslMod = loadLibPattern(DLLSSLName)
  316. except:
  317. raise newException(LibraryError, "Could not load SSL using " & DLLSSLName)
  318. result = sslMod
  319. proc utilModule(): LibHandle {.inline.} =
  320. var utilMod {.global.}: LibHandle
  321. if utilMod.isNil: utilMod = loadLibPattern(DLLUtilName)
  322. result = utilMod
  323. proc symNullable(dll: LibHandle, name: string, alternativeName = ""): pointer =
  324. # Load from DLL.
  325. if not dll.isNil:
  326. result = symAddr(dll, name)
  327. if result.isNil and alternativeName.len > 0:
  328. result = symAddr(dll, alternativeName)
  329. # Attempt to load from current exe.
  330. if result.isNil:
  331. let thisDynlib = thisModule()
  332. if thisDynlib.isNil: return nil
  333. result = symAddr(thisDynlib, name)
  334. if result.isNil and alternativeName.len > 0:
  335. result = symAddr(thisDynlib, alternativeName)
  336. proc sslSymNullable(name: string, alternativeName = ""): pointer {.raises: [LibraryError], tags:[RootEffect].} =
  337. sslModule().symNullable(name, alternativeName)
  338. proc sslSymThrows(name: string, alternativeName = ""): pointer {.raises: [LibraryError].} =
  339. result = sslSymNullable(name, alternativeName)
  340. if result.isNil: raiseInvalidLibrary(name)
  341. proc utilSymNullable(name: string, alternativeName = ""): pointer =
  342. utilModule().symNullable(name, alternativeName)
  343. proc loadPSSLMethod(method1, method2: string): PSSL_METHOD {.raises: [LibraryError], tags:[RootEffect].} =
  344. ## Load <method1> from OpenSSL if available, otherwise <method2>
  345. ##
  346. let methodSym = sslSymNullable(method1, method2)
  347. if methodSym.isNil:
  348. raise newException(LibraryError, "Could not load " & method1 & " nor " & method2)
  349. let method2Proc = cast[proc(): PSSL_METHOD {.cdecl, gcsafe, raises: [].}](methodSym)
  350. return method2Proc()
  351. proc CRYPTO_set_mem_functions(a,b,c: pointer) =
  352. let theProc = cast[proc(a,b,c: pointer) {.cdecl.}](utilModule().symNullable("CRYPTO_set_mem_functions"))
  353. if not theProc.isNil: theProc(a, b, c)
  354. proc SSL_library_init*(): cint {.discardable.} =
  355. ## Initialize SSL using OPENSSL_init_ssl for OpenSSL >= 1.1.0 otherwise
  356. ## SSL_library_init
  357. let newInitSym = sslSymNullable("OPENSSL_init_ssl")
  358. if not newInitSym.isNil:
  359. let newInitProc =
  360. cast[proc(opts: uint64, settings: uint8): cint {.cdecl.}](newInitSym)
  361. return newInitProc(0, 0)
  362. let olderProc = cast[proc(): cint {.cdecl.}](sslSymThrows("SSL_library_init"))
  363. if not olderProc.isNil: result = olderProc()
  364. proc SSL_load_error_strings*() =
  365. # TODO: Are we ignoring this on purpose? SSL GitHub CI fails otherwise.
  366. let theProc = cast[proc() {.cdecl.}](sslSymNullable("SSL_load_error_strings"))
  367. if not theProc.isNil: theProc()
  368. proc ERR_load_BIO_strings*() =
  369. let theProc = cast[proc() {.cdecl.}](utilModule().symNullable("ERR_load_BIO_strings"))
  370. if not theProc.isNil: theProc()
  371. proc SSLv23_client_method*(): PSSL_METHOD =
  372. loadPSSLMethod("SSLv23_client_method", "TLS_client_method")
  373. proc SSLv23_method*(): PSSL_METHOD =
  374. loadPSSLMethod("SSLv23_method", "TLS_method")
  375. proc SSLv2_method*(): PSSL_METHOD =
  376. loadPSSLMethod("SSLv2_method", "TLS_method")
  377. proc SSLv3_method*(): PSSL_METHOD =
  378. loadPSSLMethod("SSLv3_method", "TLS_method")
  379. proc TLS_method*(): PSSL_METHOD =
  380. loadPSSLMethod("TLS_method", "SSLv23_method")
  381. proc TLS_client_method*(): PSSL_METHOD =
  382. loadPSSLMethod("TLS_client_method", "SSLv23_client_method")
  383. proc TLS_server_method*(): PSSL_METHOD =
  384. loadPSSLMethod("TLS_server_method", "SSLv23_server_method")
  385. proc OpenSSL_add_all_algorithms*() =
  386. # TODO: Are we ignoring this on purpose? SSL GitHub CI fails otherwise.
  387. let theProc = cast[proc() {.cdecl.}](sslSymNullable("OPENSSL_add_all_algorithms_conf"))
  388. if not theProc.isNil: theProc()
  389. proc getOpenSSLVersion*(): culong =
  390. ## Return OpenSSL version as unsigned long or 0 if not available
  391. let theProc = cast[proc(): culong {.cdecl, gcsafe.}](utilSymNullable("OpenSSL_version_num", "SSLeay"))
  392. result =
  393. if theProc.isNil: 0.culong
  394. else: theProc()
  395. proc SSL_in_init*(ssl: SslPtr): cint =
  396. # A compatibility wrapper for `SSL_in_init()` for OpenSSL 1.0, 1.1 and LibreSSL
  397. const MainProc = "SSL_in_init"
  398. let
  399. theProc {.global.} = cast[proc(ssl: SslPtr): cint {.cdecl, gcsafe.}](sslSymNullable(MainProc))
  400. # Fallback
  401. sslState {.global.} = cast[proc(ssl: SslPtr): cint {.cdecl, gcsafe.}](sslSymNullable("SSL_state"))
  402. if not theProc.isNil:
  403. result = theProc(ssl)
  404. elif not sslState.isNil:
  405. result = sslState(ssl) and SSL_ST_INIT
  406. else:
  407. raiseInvalidLibrary MainProc
  408. proc SSL_CTX_set_ciphersuites*(ctx: SslCtx, str: cstring): cint =
  409. var theProc {.global.}: proc(ctx: SslCtx, str: cstring): cint {.cdecl, gcsafe.}
  410. if theProc.isNil:
  411. theProc = cast[typeof(theProc)](sslSymThrows("SSL_CTX_set_ciphersuites"))
  412. result = theProc(ctx, str)
  413. proc SSL_new*(context: SslCtx): SslPtr{.cdecl, dynlib: DLLSSLName, importc.}
  414. proc SSL_free*(ssl: SslPtr){.cdecl, dynlib: DLLSSLName, importc.}
  415. proc SSL_get_SSL_CTX*(ssl: SslPtr): SslCtx {.cdecl, dynlib: DLLSSLName, importc.}
  416. proc SSL_set_SSL_CTX*(ssl: SslPtr, ctx: SslCtx): SslCtx {.cdecl, dynlib: DLLSSLName, importc.}
  417. proc SSL_CTX_set_session_id_context*(context: SslCtx, sid_ctx: string, sid_ctx_len: int){.cdecl, dynlib: DLLSSLName, importc.}
  418. proc SSL_get0_verified_chain*(ssl: SslPtr): PSTACK {.cdecl, dynlib: DLLSSLName,
  419. importc.}
  420. proc SSL_CTX_new*(meth: PSSL_METHOD): SslCtx{.cdecl,
  421. dynlib: DLLSSLName, importc.}
  422. proc SSL_CTX_load_verify_locations*(ctx: SslCtx, CAfile: cstring,
  423. CApath: cstring): cint{.cdecl, dynlib: DLLSSLName, importc.}
  424. proc SSL_CTX_free*(arg0: SslCtx){.cdecl, dynlib: DLLSSLName, importc.}
  425. proc SSL_CTX_set_verify*(s: SslCtx, mode: int, cb: proc (a: int, b: pointer): int {.cdecl.}){.cdecl, dynlib: DLLSSLName, importc.}
  426. proc SSL_get_verify_result*(ssl: SslPtr): int{.cdecl,
  427. dynlib: DLLSSLName, importc.}
  428. proc SSL_CTX_set_cipher_list*(s: SslCtx, ciphers: cstring): cint{.cdecl, dynlib: DLLSSLName, importc.}
  429. proc SSL_CTX_use_certificate_file*(ctx: SslCtx, filename: cstring, typ: cint): cint{.
  430. stdcall, dynlib: DLLSSLName, importc.}
  431. proc SSL_CTX_use_certificate_chain_file*(ctx: SslCtx, filename: cstring): cint{.
  432. stdcall, dynlib: DLLSSLName, importc.}
  433. proc SSL_CTX_use_PrivateKey_file*(ctx: SslCtx,
  434. filename: cstring, typ: cint): cint{.cdecl, dynlib: DLLSSLName, importc.}
  435. proc SSL_CTX_check_private_key*(ctx: SslCtx): cint{.cdecl, dynlib: DLLSSLName,
  436. importc.}
  437. proc SSL_CTX_get_ex_new_index*(argl: clong, argp: pointer, new_func: pointer, dup_func: pointer, free_func: pointer): cint {.cdecl, dynlib: DLLSSLName, importc.}
  438. proc SSL_CTX_set_ex_data*(ssl: SslCtx, idx: cint, arg: pointer): cint {.cdecl, dynlib: DLLSSLName, importc.}
  439. proc SSL_CTX_get_ex_data*(ssl: SslCtx, idx: cint): pointer {.cdecl, dynlib: DLLSSLName, importc.}
  440. proc SSL_set_fd*(ssl: SslPtr, fd: SocketHandle): cint{.cdecl, dynlib: DLLSSLName, importc.}
  441. proc SSL_shutdown*(ssl: SslPtr): cint{.cdecl, dynlib: DLLSSLName, importc.}
  442. proc SSL_set_shutdown*(ssl: SslPtr, mode: cint) {.cdecl, dynlib: DLLSSLName, importc: "SSL_set_shutdown".}
  443. proc SSL_get_shutdown*(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName, importc: "SSL_get_shutdown".}
  444. proc SSL_connect*(ssl: SslPtr): cint{.cdecl, dynlib: DLLSSLName, importc.}
  445. proc SSL_read*(ssl: SslPtr, buf: pointer, num: int): cint{.cdecl, dynlib: DLLSSLName, importc.}
  446. proc SSL_write*(ssl: SslPtr, buf: cstring, num: int): cint{.cdecl, dynlib: DLLSSLName, importc.}
  447. proc SSL_get_error*(s: SslPtr, ret_code: cint): cint{.cdecl, dynlib: DLLSSLName, importc.}
  448. proc SSL_accept*(ssl: SslPtr): cint{.cdecl, dynlib: DLLSSLName, importc.}
  449. proc SSL_pending*(ssl: SslPtr): cint{.cdecl, dynlib: DLLSSLName, importc.}
  450. proc BIO_new_mem_buf*(data: pointer, len: cint): BIO{.cdecl,
  451. dynlib: DLLUtilName, importc.}
  452. proc BIO_new_ssl_connect*(ctx: SslCtx): BIO{.cdecl,
  453. dynlib: DLLSSLName, importc.}
  454. proc BIO_ctrl*(bio: BIO, cmd: cint, larg: int, arg: cstring): int{.cdecl,
  455. dynlib: DLLUtilName, importc.}
  456. proc BIO_get_ssl*(bio: BIO, ssl: ptr SslPtr): int =
  457. return BIO_ctrl(bio, BIO_C_GET_SSL, 0, cast[cstring](ssl))
  458. proc BIO_set_conn_hostname*(bio: BIO, name: cstring): int =
  459. return BIO_ctrl(bio, BIO_C_SET_CONNECT, 0, name)
  460. proc BIO_do_handshake*(bio: BIO): int =
  461. return BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, nil)
  462. proc BIO_do_connect*(bio: BIO): int =
  463. return BIO_do_handshake(bio)
  464. proc BIO_read*(b: BIO, data: cstring, length: cint): cint{.cdecl, dynlib: DLLUtilName, importc.}
  465. proc BIO_write*(b: BIO, data: cstring, length: cint): cint{.cdecl, dynlib: DLLUtilName, importc.}
  466. proc BIO_free*(b: BIO): cint{.cdecl, dynlib: DLLUtilName, importc.}
  467. proc ERR_print_errors_fp*(fp: File){.cdecl, dynlib: DLLUtilName, importc.}
  468. proc ERR_error_string*(e: culong, buf: cstring): cstring{.cdecl,
  469. dynlib: DLLUtilName, importc.}
  470. proc ERR_get_error*(): culong{.cdecl, dynlib: DLLUtilName, importc.}
  471. proc ERR_peek_last_error*(): culong{.cdecl, dynlib: DLLUtilName, importc.}
  472. proc OPENSSL_config*(configName: cstring){.cdecl, dynlib: DLLUtilName, importc.}
  473. proc OPENSSL_sk_num*(stack: PSTACK): int {.cdecl, dynlib: DLLSSLName, importc.}
  474. proc OPENSSL_sk_value*(stack: PSTACK, index: int): pointer {.cdecl,
  475. dynlib: DLLSSLName, importc.}
  476. proc d2i_X509*(px: ptr PX509, i: ptr ptr uint8, len: cint): PX509 {.cdecl,
  477. dynlib: DLLUtilName, importc.}
  478. proc i2d_X509*(cert: PX509; o: ptr ptr uint8): cint {.cdecl,
  479. dynlib: DLLUtilName, importc.}
  480. proc d2i_X509*(b: string): PX509 =
  481. ## decode DER/BER bytestring into X.509 certificate struct
  482. var bb = b.cstring
  483. let i = cast[ptr ptr uint8](addr bb)
  484. let ret = d2i_X509(addr result, i, b.len.cint)
  485. if ret.isNil:
  486. raise newException(Exception, "X.509 certificate decoding failed")
  487. proc i2d_X509*(cert: PX509): string =
  488. ## encode `cert` to DER string
  489. let encoded_length = i2d_X509(cert, nil)
  490. result = newString(encoded_length)
  491. var q = result.cstring
  492. let o = cast[ptr ptr uint8](addr q)
  493. let length = i2d_X509(cert, o)
  494. if length.int <= 0:
  495. raise newException(Exception, "X.509 certificate encoding failed")
  496. const
  497. useNimsAlloc = not defined(nimNoAllocForSSL) and not defined(gcDestructors)
  498. when not useWinVersion and not defined(macosx) and not defined(android) and useNimsAlloc:
  499. proc allocWrapper(size: int): pointer {.cdecl.} = allocShared(size)
  500. proc reallocWrapper(p: pointer; newSize: int): pointer {.cdecl.} =
  501. if p == nil:
  502. if newSize > 0: result = allocShared(newSize)
  503. elif newSize == 0: deallocShared(p)
  504. else: result = reallocShared(p, newSize)
  505. proc deallocWrapper(p: pointer) {.cdecl.} =
  506. if p != nil: deallocShared(p)
  507. proc CRYPTO_malloc_init*() =
  508. CRYPTO_set_mem_functions(cast[pointer](allocWrapper), cast[pointer](reallocWrapper), cast[pointer](deallocWrapper))
  509. else:
  510. proc CRYPTO_malloc_init*() =
  511. discard
  512. proc SSL_CTX_ctrl*(ctx: SslCtx, cmd: cint, larg: clong, parg: pointer): clong{.
  513. cdecl, dynlib: DLLSSLName, importc.}
  514. proc SSL_CTX_callback_ctrl(ctx: SslCtx, typ: cint, fp: PFunction): int{.
  515. cdecl, dynlib: DLLSSLName, importc.}
  516. proc SSLCTXSetMode*(ctx: SslCtx, mode: int): int =
  517. result = SSL_CTX_ctrl(ctx, SSL_CTRL_MODE, clong mode, nil)
  518. proc SSL_ctrl*(ssl: SslPtr, cmd: cint, larg: int, parg: pointer): int{.
  519. cdecl, dynlib: DLLSSLName, importc.}
  520. proc SSL_set_tlsext_host_name*(ssl: SslPtr, name: cstring): int =
  521. ## Set the SNI server name extension to be used in a client hello.
  522. ## Returns 1 if SNI was set, 0 if current SSL configuration doesn't support SNI.
  523. result = SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, name)
  524. proc SSL_get_servername*(ssl: SslPtr, typ: cint = TLSEXT_NAMETYPE_host_name): cstring {.cdecl, dynlib: DLLSSLName, importc.}
  525. ## Retrieve the server name requested in the client hello. This can be used
  526. ## in the callback set in `SSL_CTX_set_tlsext_servername_callback` to
  527. ## implement virtual hosting. May return `nil`.
  528. proc SSL_CTX_set_tlsext_servername_callback*(ctx: SslCtx, cb: proc(ssl: SslPtr, cb_id: int, arg: pointer): int {.cdecl.}): int =
  529. ## Set the callback to be used on listening SSL connections when the client hello is received.
  530. ##
  531. ## The callback should return one of:
  532. ## * SSL_TLSEXT_ERR_OK
  533. ## * SSL_TLSEXT_ERR_ALERT_WARNING
  534. ## * SSL_TLSEXT_ERR_ALERT_FATAL
  535. ## * SSL_TLSEXT_ERR_NOACK
  536. result = SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, cast[PFunction](cb))
  537. proc SSL_CTX_set_tlsext_servername_arg*(ctx: SslCtx, arg: pointer): int =
  538. ## Set the pointer to be used in the callback registered to `SSL_CTX_set_tlsext_servername_callback`.
  539. result = SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, arg)
  540. type
  541. PskClientCallback* = proc (ssl: SslPtr;
  542. hint: cstring; identity: cstring; max_identity_len: cuint; psk: ptr uint8;
  543. max_psk_len: cuint): cuint {.cdecl.}
  544. PskServerCallback* = proc (ssl: SslPtr;
  545. identity: cstring; psk: ptr uint8; max_psk_len: cint): cuint {.cdecl.}
  546. proc SSL_CTX_set_psk_client_callback*(ctx: SslCtx; callback: PskClientCallback) {.cdecl, dynlib: DLLSSLName, importc.}
  547. ## Set callback called when OpenSSL needs PSK (for client).
  548. proc SSL_CTX_set_psk_server_callback*(ctx: SslCtx; callback: PskServerCallback) {.cdecl, dynlib: DLLSSLName, importc.}
  549. ## Set callback called when OpenSSL needs PSK (for server).
  550. proc SSL_CTX_use_psk_identity_hint*(ctx: SslCtx; hint: cstring): cint {.cdecl, dynlib: DLLSSLName, importc.}
  551. ## Set PSK identity hint to use.
  552. proc SSL_get_psk_identity*(ssl: SslPtr): cstring {.cdecl, dynlib: DLLSSLName, importc.}
  553. ## Get PSK identity.
  554. proc SSL_CTX_set_ecdh_auto*(ctx: SslCtx, onoff: cint): cint {.inline.} =
  555. ## Set automatic curve selection.
  556. ##
  557. ## On OpenSSL >= 1.1.0 this is on by default and cannot be disabled.
  558. if getOpenSSLVersion() < 0x010100000 or getOpenSSLVersion() == 0x020000000:
  559. result = cint SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, nil)
  560. else:
  561. result = 1
  562. proc bioNew*(b: PBIO_METHOD): BIO{.cdecl, dynlib: DLLUtilName, importc: "BIO_new".}
  563. proc bioFreeAll*(b: BIO){.cdecl, dynlib: DLLUtilName, importc: "BIO_free_all".}
  564. proc bioSMem*(): PBIO_METHOD{.cdecl, dynlib: DLLUtilName, importc: "BIO_s_mem".}
  565. proc bioCtrlPending*(b: BIO): cint{.cdecl, dynlib: DLLUtilName, importc: "BIO_ctrl_pending".}
  566. proc bioRead*(b: BIO, Buf: cstring, length: cint): cint{.cdecl,
  567. dynlib: DLLUtilName, importc: "BIO_read".}
  568. proc bioWrite*(b: BIO, Buf: cstring, length: cint): cint{.cdecl,
  569. dynlib: DLLUtilName, importc: "BIO_write".}
  570. proc sslSetConnectState*(s: SslPtr) {.cdecl,
  571. dynlib: DLLSSLName, importc: "SSL_set_connect_state".}
  572. proc sslSetAcceptState*(s: SslPtr) {.cdecl,
  573. dynlib: DLLSSLName, importc: "SSL_set_accept_state".}
  574. proc sslRead*(ssl: SslPtr, buf: cstring, num: cint): cint{.cdecl,
  575. dynlib: DLLSSLName, importc: "SSL_read".}
  576. proc sslPeek*(ssl: SslPtr, buf: cstring, num: cint): cint{.cdecl,
  577. dynlib: DLLSSLName, importc: "SSL_peek".}
  578. proc sslWrite*(ssl: SslPtr, buf: cstring, num: cint): cint{.cdecl,
  579. dynlib: DLLSSLName, importc: "SSL_write".}
  580. proc sslSetBio*(ssl: SslPtr, rbio, wbio: BIO) {.cdecl,
  581. dynlib: DLLSSLName, importc: "SSL_set_bio".}
  582. proc sslDoHandshake*(ssl: SslPtr): cint {.cdecl,
  583. dynlib: DLLSSLName, importc: "SSL_do_handshake".}
  584. proc ErrClearError*(){.cdecl, dynlib: DLLUtilName, importc: "ERR_clear_error".}
  585. proc ErrFreeStrings*(){.cdecl, dynlib: DLLUtilName, importc: "ERR_free_strings".}
  586. proc ErrRemoveState*(pid: cint){.cdecl, dynlib: DLLUtilName, importc: "ERR_remove_state".}
  587. proc PEM_read_bio_RSA_PUBKEY*(bp: BIO, x: ptr PRSA, pw: pem_password_cb, u: pointer): PRSA {.cdecl,
  588. dynlib: DLLUtilName, importc.}
  589. proc PEM_read_RSA_PUBKEY*(fp: pointer; x: ptr PRSA; cb: pem_password_cb, u: pointer): PRSA {.cdecl,
  590. dynlib: DLLUtilName, importc.}
  591. proc RSA_verify*(kind: cint, origMsg: pointer, origMsgLen: cuint, signature: pointer,
  592. signatureLen: cuint, rsa: PRSA): cint {.cdecl, dynlib: DLLUtilName, importc.}
  593. proc PEM_read_RSAPrivateKey*(fp: pointer; x: ptr PRSA; cb: pem_password_cb, u: pointer): PRSA {.cdecl,
  594. dynlib: DLLUtilName, importc.}
  595. proc PEM_read_RSAPublicKey*(fp: pointer; x: ptr PRSA; cb: pem_password_cb, u: pointer): PRSA {.cdecl,
  596. dynlib: DLLUtilName, importc.}
  597. proc PEM_read_bio_RSAPublicKey*(bp: BIO, x: ptr PRSA, cb: pem_password_cb, u: pointer): PRSA {.cdecl,
  598. dynlib: DLLUtilName, importc.}
  599. proc PEM_read_bio_RSAPrivateKey*(bp: BIO, x: ptr PRSA, cb: pem_password_cb, u: pointer): PRSA {.cdecl,
  600. dynlib: DLLUtilName, importc.}
  601. proc RSA_private_encrypt*(flen: cint, fr: ptr uint8, to: ptr uint8, rsa: PRSA, padding: PaddingType): cint {.cdecl,
  602. dynlib: DLLUtilName, importc.}
  603. proc RSA_public_encrypt*(flen: cint, fr: ptr uint8, to: ptr uint8, rsa: PRSA, padding: PaddingType): cint {.cdecl,
  604. dynlib: DLLUtilName, importc.}
  605. proc RSA_private_decrypt*(flen: cint, fr: ptr uint8, to: ptr uint8, rsa: PRSA, padding: PaddingType): cint {.cdecl,
  606. dynlib: DLLUtilName, importc.}
  607. proc RSA_public_decrypt*(flen: cint, fr: ptr uint8, to: ptr uint8, rsa: PRSA, padding: PaddingType): cint {.cdecl,
  608. dynlib: DLLUtilName, importc.}
  609. proc RSA_free*(rsa: PRSA) {.cdecl, dynlib: DLLUtilName, importc.}
  610. proc RSA_size*(rsa: PRSA): cint {.cdecl, dynlib: DLLUtilName, importc.}
  611. # sha types
  612. proc EVP_md_null*(): EVP_MD {.lcrypto.}
  613. proc EVP_md2*(): EVP_MD {.lcrypto.}
  614. proc EVP_md4*(): EVP_MD {.lcrypto.}
  615. proc EVP_md5*(): EVP_MD {.lcrypto.}
  616. proc EVP_sha*(): EVP_MD {.lcrypto.}
  617. proc EVP_sha1*(): EVP_MD {.lcrypto.}
  618. proc EVP_dss*(): EVP_MD {.lcrypto.}
  619. proc EVP_dss1*(): EVP_MD {.lcrypto.}
  620. proc EVP_ecdsa*(): EVP_MD {.lcrypto.}
  621. proc EVP_sha224*(): EVP_MD {.lcrypto.}
  622. proc EVP_sha256*(): EVP_MD {.lcrypto.}
  623. proc EVP_sha384*(): EVP_MD {.lcrypto.}
  624. proc EVP_sha512*(): EVP_MD {.lcrypto.}
  625. proc EVP_mdc2*(): EVP_MD {.lcrypto.}
  626. proc EVP_ripemd160*(): EVP_MD {.lcrypto.}
  627. proc EVP_whirlpool*(): EVP_MD {.lcrypto.}
  628. proc EVP_MD_size*(md: EVP_MD): cint {.lcrypto.}
  629. # hmac functions
  630. proc HMAC*(evp_md: EVP_MD; key: pointer; key_len: cint; d: cstring; n: csize_t; md: cstring; md_len: ptr cuint): cstring {.lcrypto.}
  631. # RSA key functions
  632. proc PEM_read_bio_PrivateKey*(bp: BIO, x: ptr EVP_PKEY, cb: pointer, u: pointer): EVP_PKEY {.lcrypto.}
  633. proc EVP_PKEY_free*(p: EVP_PKEY) {.lcrypto.}
  634. proc EVP_DigestSignInit*(ctx: EVP_MD_CTX, pctx: ptr EVP_PKEY_CTX, typ: EVP_MD, e: ENGINE, pkey: EVP_PKEY): cint {.lcrypto.}
  635. proc EVP_DigestInit_ex*(ctx: EVP_MD_CTX, typ: EVP_MD, engine: SslPtr = nil): cint {.lcrypto.}
  636. proc EVP_DigestUpdate*(ctx: EVP_MD_CTX, data: pointer, len: cuint): cint {.lcrypto.}
  637. proc EVP_DigestFinal_ex*(ctx: EVP_MD_CTX, buffer: pointer, size: ptr cuint): cint {.lcrypto.}
  638. proc EVP_DigestSignFinal*(ctx: EVP_MD_CTX, data: pointer, len: ptr csize_t): cint {.lcrypto.}
  639. proc EVP_PKEY_CTX_new*(pkey: EVP_PKEY, e: ENGINE): EVP_PKEY_CTX {.lcrypto.}
  640. proc EVP_PKEY_CTX_free*(pkeyCtx: EVP_PKEY_CTX) {.lcrypto.}
  641. proc EVP_PKEY_sign_init*(c: EVP_PKEY_CTX): cint {.lcrypto.}
  642. when defined(macosx) or defined(windows):
  643. proc EVP_MD_CTX_create*(): EVP_MD_CTX {.lcrypto.}
  644. proc EVP_MD_CTX_destroy*(ctx: EVP_MD_CTX) {.lcrypto.}
  645. proc EVP_MD_CTX_cleanup*(ctx: EVP_MD_CTX): cint {.lcrypto.}
  646. else:
  647. # some times you will need this instead:
  648. proc EVP_MD_CTX_create*(): EVP_MD_CTX {.cdecl, importc: "EVP_MD_CTX_new", dynlib: DLLUtilName.}
  649. proc EVP_MD_CTX_destroy*(ctx: EVP_MD_CTX) {.cdecl, importc: "EVP_MD_CTX_free", dynlib: DLLUtilName.}
  650. proc EVP_MD_CTX_cleanup*(ctx: EVP_MD_CTX): cint {.cdecl, importc: "EVP_MD_CTX_cleanup", dynlib: DLLUtilName.}
  651. # <openssl/md5.h>
  652. type
  653. MD5_LONG* = cuint
  654. const
  655. MD5_CBLOCK* = 64
  656. MD5_LBLOCK* = int(MD5_CBLOCK div 4)
  657. MD5_DIGEST_LENGTH* = 16
  658. type
  659. MD5_CTX* = object
  660. A,B,C,D,Nl,Nh: MD5_LONG
  661. data: array[MD5_LBLOCK, MD5_LONG]
  662. num: cuint
  663. {.push callconv:cdecl, dynlib:DLLUtilName.}
  664. proc md5_Init*(c: var MD5_CTX): cint{.importc: "MD5_Init".}
  665. proc md5_Update*(c: var MD5_CTX; data: pointer; len: csize_t): cint{.importc: "MD5_Update".}
  666. proc md5_Final*(md: cstring; c: var MD5_CTX): cint{.importc: "MD5_Final".}
  667. proc md5*(d: ptr uint8; n: csize_t; md: ptr uint8): ptr uint8{.importc: "MD5".}
  668. proc md5_Transform*(c: var MD5_CTX; b: ptr uint8){.importc: "MD5_Transform".}
  669. {.pop.}
  670. from std/strutils import toHex, toLowerAscii
  671. proc hexStr(buf: cstring): string =
  672. # turn md5s output into a nice hex str
  673. result = newStringOfCap(32)
  674. for i in 0 ..< 16:
  675. result.add toHex(buf[i].ord, 2).toLowerAscii
  676. proc md5_File*(file: string): string {.raises: [IOError,Exception].} =
  677. ## Generate MD5 hash for a file. Result is a 32 character
  678. # hex string with lowercase characters (like the output
  679. # of `md5sum`
  680. const
  681. sz = 512
  682. let f = open(file,fmRead)
  683. var
  684. buf: array[sz,char]
  685. ctx: MD5_CTX
  686. discard md5_Init(ctx)
  687. while (let bytes = f.readChars(buf); bytes > 0):
  688. discard md5_Update(ctx, buf[0].addr, cast[csize_t](bytes))
  689. discard md5_Final(cast[cstring](buf[0].addr), ctx)
  690. f.close
  691. result = hexStr(cast[cstring](addr buf))
  692. proc md5_Str*(str: string): string =
  693. ## Generate MD5 hash for a string. Result is a 32 character
  694. ## hex string with lowercase characters
  695. var
  696. ctx: MD5_CTX
  697. res: array[MD5_DIGEST_LENGTH,char]
  698. input = str.cstring
  699. discard md5_Init(ctx)
  700. var i = 0
  701. while i < str.len:
  702. let L = min(str.len - i, 512)
  703. discard md5_Update(ctx, input[i].addr, cast[csize_t](L))
  704. i += L
  705. discard md5_Final(cast[cstring](addr res), ctx)
  706. result = hexStr(cast[cstring](addr res))
  707. when defined(nimHasStyleChecks):
  708. {.pop.}
  709. # Certificate validation
  710. # On old openSSL version some of these symbols are not available
  711. when not defined(nimDisableCertificateValidation) and not defined(windows):
  712. # SSL_get_peer_certificate removed in 3.0
  713. # SSL_get1_peer_certificate added in 3.0
  714. when useOpenssl3:
  715. proc SSL_get1_peer_certificate*(ssl: SslCtx): PX509 {.cdecl, dynlib: DLLSSLName, importc.}
  716. proc SSL_get_peer_certificate*(ssl: SslCtx): PX509 =
  717. SSL_get1_peer_certificate(ssl)
  718. elif useStaticLink:
  719. proc SSL_get_peer_certificate*(ssl: SslCtx): PX509 {.cdecl, dynlib: DLLSSLName, importc.}
  720. else:
  721. proc SSL_get_peer_certificate*(ssl: SslCtx): PX509 =
  722. let methodSym = sslSymNullable("SSL_get_peer_certificate", "SSL_get1_peer_certificate")
  723. if methodSym.isNil:
  724. raise newException(LibraryError, "Could not load SSL_get_peer_certificate or SSL_get1_peer_certificate")
  725. let method2Proc = cast[proc(ssl: SslCtx): PX509 {.cdecl, gcsafe, raises: [].}](methodSym)
  726. return method2Proc(ssl)
  727. proc X509_get_subject_name*(a: PX509): PX509_NAME{.cdecl, dynlib: DLLSSLName, importc.}
  728. proc X509_get_issuer_name*(a: PX509): PX509_NAME{.cdecl, dynlib: DLLUtilName, importc.}
  729. proc X509_NAME_oneline*(a: PX509_NAME, buf: cstring, size: cint): cstring {.
  730. cdecl, dynlib:DLLSSLName, importc.}
  731. proc X509_NAME_get_text_by_NID*(subject:cstring, NID: cint, buf: cstring, size: cint): cint{.
  732. cdecl, dynlib:DLLSSLName, importc.}
  733. proc X509_check_host*(cert: PX509, name: cstring, namelen: cint, flags:cuint, peername: cstring): cint {.cdecl, dynlib: DLLSSLName, importc.}
  734. proc X509_free*(cert: PX509) {.cdecl, dynlib: DLLSSLName, importc.}
  735. # Certificates store
  736. type PX509_STORE* = SslPtr
  737. type PX509_OBJECT* = SslPtr
  738. {.push callconv:cdecl, dynlib:DLLUtilName, importc.}
  739. proc X509_OBJECT_new*(): PX509_OBJECT
  740. proc X509_OBJECT_free*(a: PX509_OBJECT)
  741. proc X509_STORE_new*(): PX509_STORE
  742. proc X509_STORE_free*(v: PX509_STORE)
  743. proc X509_STORE_lock*(ctx: PX509_STORE): cint
  744. proc X509_STORE_unlock*(ctx: PX509_STORE): cint
  745. proc X509_STORE_up_ref*(v: PX509_STORE): cint
  746. proc X509_STORE_set_flags*(ctx: PX509_STORE; flags: culong): cint
  747. proc X509_STORE_set_purpose*(ctx: PX509_STORE; purpose: cint): cint
  748. proc X509_STORE_set_trust*(ctx: PX509_STORE; trust: cint): cint
  749. proc X509_STORE_add_cert*(ctx: PX509_STORE; x: PX509): cint
  750. {.pop.}
  751. when isMainModule:
  752. when defined(nimPreviewSlimSystem):
  753. import std/assertions
  754. # A simple certificate test
  755. let certbytes = readFile("certificate.der")
  756. let cert = d2i_X509(certbytes)
  757. let encoded = cert.i2d_X509()
  758. assert encoded == certbytes
  759. # Application Layer Protocol Negociation extension (TLS-ALPN, RFC7301)
  760. # Available in at least OpenSSL 1.1.1 and later, not sure if earlier
  761. # --Iced Quinn
  762. proc SSL_CTX_set_alpn_protos*(ctx: SslCtx; protos: cstring; protos_len: cuint): cint {.cdecl, dynlib: DLLSSLName, importc.}
  763. proc SSL_set_alpn_protos*(ssl: SslPtr; protos: cstring; protos_len: cuint): cint {.cdecl, dynlib: DLLSSLName, importc.}
  764. proc SSL_CTX_set_alpn_select_cb*(ctx: SslCtx; cb: proc(ssl: SslPtr; out_proto: ptr cstring; outlen: cstring; in_proto: cstring; inlen: cuint; arg: pointer): cint {.cdecl.}; arg: pointer): cint {.cdecl, dynlib: DLLSSLName, importc.}
  765. proc SSL_get0_alpn_selected*(ssl: SslPtr; data: ptr cstring; len: ptr cuint) {.cdecl, dynlib: DLLSSLName, importc.}
  766. proc SSL_CTX_set_next_protos_advertised_cb*(ctx: SslCtx; cb: proc(ssl: SslPtr; out_proto: ptr cstring; outlen: ptr cuint; arg: pointer): cint {.cdecl.}; arg: pointer) {.cdecl, dynlib: DLLSSLName, importc.}
  767. proc SSL_CTX_set_next_proto_select_cb*(ctx: SslCtx; cb: proc(s: SslPtr; out_proto: cstring; outlen: cstring; in_proto: cstring; inlen: cuint; arg: pointer): cint {.cdecl.}; arg: pointer) {.cdecl, dynlib: DLLSSLName, importc.}
  768. proc SSL_select_next_proto*(out_proto: ptr cstring; outlen: cstring; server: cstring; server_len: cuint; client: cstring; client_len: cuint): cint {.cdecl, dynlib: DLLSSLName, importc.}
  769. proc SSL_get0_next_proto_negotiated*(s: SslPtr; data: ptr cstring; len: ptr cuint) {.cdecl, dynlib: DLLSSLName, importc.}