openssl.nim 34 KB

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