openssl.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  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. {.deadCodeElim: on.} # dce option deprecated
  24. const useWinVersion = defined(Windows) or defined(nimdoc)
  25. when useWinVersion:
  26. when not defined(nimOldDlls) and defined(cpu64):
  27. const
  28. DLLSSLName* = "(libssl-1_1-x64|ssleay64|libssl64).dll"
  29. DLLUtilName* = "(libcrypto-1_1-x64|libeay64).dll"
  30. else:
  31. const
  32. DLLSSLName* = "(libssl-1_1|ssleay32|libssl32).dll"
  33. DLLUtilName* = "(libcrypto-1_1|libeay32).dll"
  34. from winlean import SocketHandle
  35. else:
  36. const versions = "(.1.1|.38|.39|.41|.43|.44|.45|.46|.10|.1.0.2|.1.0.1|.1.0.0|.0.9.9|.0.9.8|)"
  37. when defined(macosx):
  38. const
  39. DLLSSLName* = "libssl" & versions & ".dylib"
  40. DLLUtilName* = "libcrypto" & versions & ".dylib"
  41. elif defined(genode):
  42. const
  43. DLLSSLName* = "libssl.lib.so"
  44. DLLUtilName* = "libcrypto.lib.so"
  45. else:
  46. const
  47. DLLSSLName* = "libssl.so" & versions
  48. DLLUtilName* = "libcrypto.so" & versions
  49. from posix import SocketHandle
  50. import dynlib
  51. type
  52. SslStruct {.final, pure.} = object
  53. SslPtr* = ptr SslStruct
  54. PSslPtr* = ptr SslPtr
  55. SslCtx* = SslPtr
  56. PSSL_METHOD* = SslPtr
  57. PX509* = SslPtr
  58. PX509_NAME* = SslPtr
  59. PEVP_MD* = SslPtr
  60. PBIO_METHOD* = SslPtr
  61. BIO* = SslPtr
  62. EVP_PKEY* = SslPtr
  63. PRSA* = SslPtr
  64. PASN1_UTCTIME* = SslPtr
  65. PASN1_cInt* = SslPtr
  66. PPasswdCb* = SslPtr
  67. PFunction* = proc () {.cdecl.}
  68. DES_cblock* = array[0..7, int8]
  69. PDES_cblock* = ptr DES_cblock
  70. des_ks_struct*{.final.} = object
  71. ks*: DES_cblock
  72. weak_key*: cInt
  73. des_key_schedule* = array[1..16, des_ks_struct]
  74. pem_password_cb* = proc(buf: cstring, size, rwflag: cint, userdata: pointer): cint {.cdecl.}
  75. const
  76. SSL_SENT_SHUTDOWN* = 1
  77. SSL_RECEIVED_SHUTDOWN* = 2
  78. EVP_MAX_MD_SIZE* = 16 + 20
  79. SSL_ERROR_NONE* = 0
  80. SSL_ERROR_SSL* = 1
  81. SSL_ERROR_WANT_READ* = 2
  82. SSL_ERROR_WANT_WRITE* = 3
  83. SSL_ERROR_WANT_X509_LOOKUP* = 4
  84. SSL_ERROR_SYSCALL* = 5 #look at error stack/return value/errno
  85. SSL_ERROR_ZERO_RETURN* = 6
  86. SSL_ERROR_WANT_CONNECT* = 7
  87. SSL_ERROR_WANT_ACCEPT* = 8
  88. SSL_CTRL_NEED_TMP_RSA* = 1
  89. SSL_CTRL_SET_TMP_RSA* = 2
  90. SSL_CTRL_SET_TMP_DH* = 3
  91. SSL_CTRL_SET_TMP_ECDH* = 4
  92. SSL_CTRL_SET_TMP_RSA_CB* = 5
  93. SSL_CTRL_SET_TMP_DH_CB* = 6
  94. SSL_CTRL_SET_TMP_ECDH_CB* = 7
  95. SSL_CTRL_GET_SESSION_REUSED* = 8
  96. SSL_CTRL_GET_CLIENT_CERT_REQUEST* = 9
  97. SSL_CTRL_GET_NUM_RENEGOTIATIONS* = 10
  98. SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS* = 11
  99. SSL_CTRL_GET_TOTAL_RENEGOTIATIONS* = 12
  100. SSL_CTRL_GET_FLAGS* = 13
  101. SSL_CTRL_EXTRA_CHAIN_CERT* = 14
  102. SSL_CTRL_SET_MSG_CALLBACK* = 15
  103. SSL_CTRL_SET_MSG_CALLBACK_ARG* = 16 # only applies to datagram connections
  104. SSL_CTRL_SET_MTU* = 17 # Stats
  105. SSL_CTRL_SESS_NUMBER* = 20
  106. SSL_CTRL_SESS_CONNECT* = 21
  107. SSL_CTRL_SESS_CONNECT_GOOD* = 22
  108. SSL_CTRL_SESS_CONNECT_RENEGOTIATE* = 23
  109. SSL_CTRL_SESS_ACCEPT* = 24
  110. SSL_CTRL_SESS_ACCEPT_GOOD* = 25
  111. SSL_CTRL_SESS_ACCEPT_RENEGOTIATE* = 26
  112. SSL_CTRL_SESS_HIT* = 27
  113. SSL_CTRL_SESS_CB_HIT* = 28
  114. SSL_CTRL_SESS_MISSES* = 29
  115. SSL_CTRL_SESS_TIMEOUTS* = 30
  116. SSL_CTRL_SESS_CACHE_FULL* = 31
  117. SSL_CTRL_OPTIONS* = 32
  118. SSL_CTRL_MODE* = 33
  119. SSL_CTRL_GET_READ_AHEAD* = 40
  120. SSL_CTRL_SET_READ_AHEAD* = 41
  121. SSL_CTRL_SET_SESS_CACHE_SIZE* = 42
  122. SSL_CTRL_GET_SESS_CACHE_SIZE* = 43
  123. SSL_CTRL_SET_SESS_CACHE_MODE* = 44
  124. SSL_CTRL_GET_SESS_CACHE_MODE* = 45
  125. SSL_CTRL_GET_MAX_CERT_LIST* = 50
  126. SSL_CTRL_SET_MAX_CERT_LIST* = 51 #* Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success
  127. # * when just a single record has been written): *
  128. SSL_CTRL_SET_TLSEXT_SERVERNAME_CB = 53
  129. SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG = 54
  130. SSL_CTRL_SET_TLSEXT_HOSTNAME = 55
  131. TLSEXT_NAMETYPE_host_name* = 0
  132. SSL_TLSEXT_ERR_OK* = 0
  133. SSL_TLSEXT_ERR_ALERT_WARNING* = 1
  134. SSL_TLSEXT_ERR_ALERT_FATAL* = 2
  135. SSL_TLSEXT_ERR_NOACK* = 3
  136. SSL_MODE_ENABLE_PARTIAL_WRITE* = 1 #* Make it possible to retry SSL_write() with changed buffer location
  137. # * (buffer contents must stay the same!); this is not the default to avoid
  138. # * the misconception that non-blocking SSL_write() behaves like
  139. # * non-blocking write(): *
  140. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER* = 2 #* Never bother the application with retries if the transport
  141. # * is blocking: *
  142. SSL_MODE_AUTO_RETRY* = 4 #* Don't attempt to automatically build certificate chain *
  143. SSL_MODE_NO_AUTO_CHAIN* = 8
  144. SSL_OP_NO_SSLv2* = 0x01000000
  145. SSL_OP_NO_SSLv3* = 0x02000000
  146. SSL_OP_NO_TLSv1* = 0x04000000
  147. SSL_OP_NO_TLSv1_1* = 0x08000000
  148. SSL_OP_ALL* = 0x000FFFFF
  149. SSL_VERIFY_NONE* = 0x00000000
  150. SSL_VERIFY_PEER* = 0x00000001
  151. OPENSSL_DES_DECRYPT* = 0
  152. OPENSSL_DES_ENCRYPT* = 1
  153. X509_V_OK* = 0
  154. X509_V_ILLEGAL* = 1
  155. X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT* = 2
  156. X509_V_ERR_UNABLE_TO_GET_CRL* = 3
  157. X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE* = 4
  158. X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE* = 5
  159. X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY* = 6
  160. X509_V_ERR_CERT_SIGNATURE_FAILURE* = 7
  161. X509_V_ERR_CRL_SIGNATURE_FAILURE* = 8
  162. X509_V_ERR_CERT_NOT_YET_VALID* = 9
  163. X509_V_ERR_CERT_HAS_EXPIRED* = 10
  164. X509_V_ERR_CRL_NOT_YET_VALID* = 11
  165. X509_V_ERR_CRL_HAS_EXPIRED* = 12
  166. X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD* = 13
  167. X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD* = 14
  168. X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD* = 15
  169. X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD* = 16
  170. X509_V_ERR_OUT_OF_MEM* = 17
  171. X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT* = 18
  172. X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN* = 19
  173. X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY* = 20
  174. X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE* = 21
  175. X509_V_ERR_CERT_CHAIN_TOO_LONG* = 22
  176. X509_V_ERR_CERT_REVOKED* = 23
  177. X509_V_ERR_INVALID_CA* = 24
  178. X509_V_ERR_PATH_LENGTH_EXCEEDED* = 25
  179. X509_V_ERR_INVALID_PURPOSE* = 26
  180. X509_V_ERR_CERT_UNTRUSTED* = 27
  181. X509_V_ERR_CERT_REJECTED* = 28 #These are 'informational' when looking for issuer cert
  182. X509_V_ERR_SUBJECT_ISSUER_MISMATCH* = 29
  183. X509_V_ERR_AKID_SKID_MISMATCH* = 30
  184. X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH* = 31
  185. X509_V_ERR_KEYUSAGE_NO_CERTSIGN* = 32
  186. X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER* = 33
  187. X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION* = 34 #The application is not happy
  188. X509_V_ERR_APPLICATION_VERIFICATION* = 50
  189. SSL_FILETYPE_ASN1* = 2
  190. SSL_FILETYPE_PEM* = 1
  191. EVP_PKEY_RSA* = 6 # libssl.dll
  192. BIO_C_SET_CONNECT = 100
  193. BIO_C_DO_STATE_MACHINE = 101
  194. BIO_C_GET_SSL = 110
  195. proc TLSv1_method*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.}
  196. # TLS_method(), TLS_server_method(), TLS_client_method() are introduced in 1.1.0
  197. # and support SSLv3, TLSv1, TLSv1.1 and TLSv1.2
  198. # SSLv23_method(), SSLv23_server_method(), SSLv23_client_method() are removed in 1.1.0
  199. when compileOption("dynlibOverride", "ssl"):
  200. # Static linking
  201. when defined(openssl10):
  202. proc SSL_library_init*(): cint {.cdecl, dynlib: DLLSSLName, importc, discardable.}
  203. proc SSL_load_error_strings*() {.cdecl, dynlib: DLLSSLName, importc.}
  204. proc SSLv23_method*(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc.}
  205. else:
  206. proc OPENSSL_init_ssl*(opts: uint64, settings: uint8): cint {.cdecl, dynlib: DLLSSLName, importc, discardable.}
  207. proc SSL_library_init*(): cint {.discardable.} =
  208. ## Initialize SSL using OPENSSL_init_ssl for OpenSSL >= 1.1.0
  209. return OPENSSL_init_ssl(0.uint64, 0.uint8)
  210. proc TLS_method*(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc.}
  211. proc SSLv23_method*(): PSSL_METHOD =
  212. TLS_method()
  213. proc OpenSSL_version_num(): culong {.cdecl, dynlib: DLLSSLName, importc.}
  214. proc getOpenSSLVersion*(): culong =
  215. ## Return OpenSSL version as unsigned long
  216. OpenSSL_version_num()
  217. proc SSL_load_error_strings*() =
  218. ## Removed from OpenSSL 1.1.0
  219. # This proc prevents breaking existing code calling SslLoadErrorStrings
  220. # Static linking against OpenSSL < 1.1.0 is not supported
  221. discard
  222. template OpenSSL_add_all_algorithms*() = discard
  223. proc SSLv23_client_method*(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc.}
  224. proc SSLv2_method*(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc.}
  225. proc SSLv3_method*(): PSSL_METHOD {.cdecl, dynlib: DLLSSLName, importc.}
  226. else:
  227. # Here we're trying to stay compatible with openssl 1.0.* and 1.1.*. Some
  228. # symbols are loaded dynamically and we don't use them if not found.
  229. proc thisModule(): LibHandle {.inline.} =
  230. var thisMod {.global.}: LibHandle
  231. if thisMod.isNil: thisMod = loadLib()
  232. result = thisMod
  233. proc sslModule(): LibHandle {.inline.} =
  234. var sslMod {.global.}: LibHandle
  235. if sslMod.isNil: sslMod = loadLibPattern(DLLSSLName)
  236. result = sslMod
  237. proc sslSym(name: string): pointer =
  238. var dl = thisModule()
  239. if not dl.isNil:
  240. result = symAddr(dl, name)
  241. if result.isNil:
  242. dl = sslModule()
  243. if not dl.isNil:
  244. result = symAddr(dl, name)
  245. proc loadPSSLMethod(method1, method2: string): PSSL_METHOD =
  246. ## Load <method1> from OpenSSL if available, otherwise <method2>
  247. let m1 = cast[proc(): PSSL_METHOD {.cdecl, gcsafe.}](sslSym(method1))
  248. if not m1.isNil:
  249. return m1()
  250. cast[proc(): PSSL_METHOD {.cdecl, gcsafe.}](sslSym(method2))()
  251. proc SSL_library_init*(): cint {.discardable.} =
  252. ## Initialize SSL using OPENSSL_init_ssl for OpenSSL >= 1.1.0 otherwise
  253. ## SSL_library_init
  254. let theProc = cast[proc(opts: uint64, settings: uint8): cint {.cdecl.}](sslSym("OPENSSL_init_ssl"))
  255. if not theProc.isNil:
  256. return theProc(0, 0)
  257. let olderProc = cast[proc(): cint {.cdecl.}](sslSym("SSL_library_init"))
  258. if not olderProc.isNil: result = olderProc()
  259. proc SSL_load_error_strings*() =
  260. let theProc = cast[proc() {.cdecl.}](sslSym("SSL_load_error_strings"))
  261. if not theProc.isNil: theProc()
  262. proc SSLv23_client_method*(): PSSL_METHOD =
  263. loadPSSLMethod("SSLv23_client_method", "TLS_client_method")
  264. proc SSLv23_method*(): PSSL_METHOD =
  265. loadPSSLMethod("SSLv23_method", "TLS_method")
  266. proc SSLv2_method*(): PSSL_METHOD =
  267. loadPSSLMethod("SSLv2_method", "TLS_method")
  268. proc SSLv3_method*(): PSSL_METHOD =
  269. loadPSSLMethod("SSLv3_method", "TLS_method")
  270. proc TLS_method*(): PSSL_METHOD =
  271. loadPSSLMethod("TLS_method", "SSLv23_method")
  272. proc TLS_client_method*(): PSSL_METHOD =
  273. loadPSSLMethod("TLS_client_method", "SSLv23_client_method")
  274. proc TLS_server_method*(): PSSL_METHOD =
  275. loadPSSLMethod("TLS_server_method", "SSLv23_server_method")
  276. proc OpenSSL_add_all_algorithms*() =
  277. let theProc = cast[proc() {.cdecl.}](sslSym("OPENSSL_add_all_algorithms_conf"))
  278. if not theProc.isNil: theProc()
  279. proc getOpenSSLVersion*(): culong =
  280. ## Return OpenSSL version as unsigned long or 0 if not available
  281. let theProc = cast[proc(): culong {.cdecl.}](sslSym("OpenSSL_version_num"))
  282. result =
  283. if theProc.isNil: 0.culong
  284. else: theProc()
  285. proc ERR_load_BIO_strings*(){.cdecl, dynlib: DLLUtilName, importc.}
  286. proc SSL_new*(context: SslCtx): SslPtr{.cdecl, dynlib: DLLSSLName, importc.}
  287. proc SSL_free*(ssl: SslPtr){.cdecl, dynlib: DLLSSLName, importc.}
  288. proc SSL_get_SSL_CTX*(ssl: SslPtr): SslCtx {.cdecl, dynlib: DLLSSLName, importc.}
  289. proc SSL_set_SSL_CTX*(ssl: SslPtr, ctx: SslCtx): SslCtx {.cdecl, dynlib: DLLSSLName, importc.}
  290. proc SSL_CTX_new*(meth: PSSL_METHOD): SslCtx{.cdecl,
  291. dynlib: DLLSSLName, importc.}
  292. proc SSL_CTX_load_verify_locations*(ctx: SslCtx, CAfile: cstring,
  293. CApath: cstring): cInt{.cdecl, dynlib: DLLSSLName, importc.}
  294. proc SSL_CTX_free*(arg0: SslCtx){.cdecl, dynlib: DLLSSLName, importc.}
  295. proc SSL_CTX_set_verify*(s: SslCtx, mode: int, cb: proc (a: int, b: pointer): int {.cdecl.}){.cdecl, dynlib: DLLSSLName, importc.}
  296. proc SSL_get_verify_result*(ssl: SslPtr): int{.cdecl,
  297. dynlib: DLLSSLName, importc.}
  298. proc SSL_CTX_set_cipher_list*(s: SslCtx, ciphers: cstring): cint{.cdecl, dynlib: DLLSSLName, importc.}
  299. proc SSL_CTX_use_certificate_file*(ctx: SslCtx, filename: cstring, typ: cInt): cInt{.
  300. stdcall, dynlib: DLLSSLName, importc.}
  301. proc SSL_CTX_use_certificate_chain_file*(ctx: SslCtx, filename: cstring): cInt{.
  302. stdcall, dynlib: DLLSSLName, importc.}
  303. proc SSL_CTX_use_PrivateKey_file*(ctx: SslCtx,
  304. filename: cstring, typ: cInt): cInt{.cdecl, dynlib: DLLSSLName, importc.}
  305. proc SSL_CTX_check_private_key*(ctx: SslCtx): cInt{.cdecl, dynlib: DLLSSLName,
  306. importc.}
  307. 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.}
  308. proc SSL_CTX_set_ex_data*(ssl: SslCtx, idx: cint, arg: pointer): cint {.cdecl, dynlib: DLLSSLName, importc.}
  309. proc SSL_CTX_get_ex_data*(ssl: SslCtx, idx: cint): pointer {.cdecl, dynlib: DLLSSLName, importc.}
  310. proc SSL_set_fd*(ssl: SslPtr, fd: SocketHandle): cint{.cdecl, dynlib: DLLSSLName, importc.}
  311. proc SSL_shutdown*(ssl: SslPtr): cInt{.cdecl, dynlib: DLLSSLName, importc.}
  312. proc SSL_set_shutdown*(ssl: SslPtr, mode: cint) {.cdecl, dynlib: DLLSSLName, importc: "SSL_set_shutdown".}
  313. proc SSL_get_shutdown*(ssl: SslPtr): cint {.cdecl, dynlib: DLLSSLName, importc: "SSL_get_shutdown".}
  314. proc SSL_connect*(ssl: SslPtr): cint{.cdecl, dynlib: DLLSSLName, importc.}
  315. proc SSL_read*(ssl: SslPtr, buf: pointer, num: int): cint{.cdecl, dynlib: DLLSSLName, importc.}
  316. proc SSL_write*(ssl: SslPtr, buf: cstring, num: int): cint{.cdecl, dynlib: DLLSSLName, importc.}
  317. proc SSL_get_error*(s: SslPtr, ret_code: cInt): cInt{.cdecl, dynlib: DLLSSLName, importc.}
  318. proc SSL_accept*(ssl: SslPtr): cInt{.cdecl, dynlib: DLLSSLName, importc.}
  319. proc SSL_pending*(ssl: SslPtr): cInt{.cdecl, dynlib: DLLSSLName, importc.}
  320. proc BIO_new_mem_buf*(data: pointer, len: cint): BIO{.cdecl,
  321. dynlib: DLLSSLName, importc.}
  322. proc BIO_new_ssl_connect*(ctx: SslCtx): BIO{.cdecl,
  323. dynlib: DLLSSLName, importc.}
  324. proc BIO_ctrl*(bio: BIO, cmd: cint, larg: int, arg: cstring): int{.cdecl,
  325. dynlib: DLLSSLName, importc.}
  326. proc BIO_get_ssl*(bio: BIO, ssl: ptr SslPtr): int =
  327. return BIO_ctrl(bio, BIO_C_GET_SSL, 0, cast[cstring](ssl))
  328. proc BIO_set_conn_hostname*(bio: BIO, name: cstring): int =
  329. return BIO_ctrl(bio, BIO_C_SET_CONNECT, 0, name)
  330. proc BIO_do_handshake*(bio: BIO): int =
  331. return BIO_ctrl(bio, BIO_C_DO_STATE_MACHINE, 0, nil)
  332. proc BIO_do_connect*(bio: BIO): int =
  333. return BIO_do_handshake(bio)
  334. when not defined(nimfix):
  335. proc BIO_read*(b: BIO, data: cstring, length: cInt): cInt{.cdecl,
  336. dynlib: DLLUtilName, importc.}
  337. proc BIO_write*(b: BIO, data: cstring, length: cInt): cInt{.cdecl,
  338. dynlib: DLLUtilName, importc.}
  339. proc BIO_free*(b: BIO): cInt{.cdecl, dynlib: DLLUtilName, importc.}
  340. proc ERR_print_errors_fp*(fp: File){.cdecl, dynlib: DLLSSLName, importc.}
  341. proc ERR_error_string*(e: cInt, buf: cstring): cstring{.cdecl,
  342. dynlib: DLLUtilName, importc.}
  343. proc ERR_get_error*(): cInt{.cdecl, dynlib: DLLUtilName, importc.}
  344. proc ERR_peek_last_error*(): cInt{.cdecl, dynlib: DLLUtilName, importc.}
  345. proc OPENSSL_config*(configName: cstring){.cdecl, dynlib: DLLSSLName, importc.}
  346. when not useWinVersion and not defined(macosx) and not defined(android) and not defined(nimNoAllocForSSL):
  347. proc CRYPTO_set_mem_functions(a,b,c: pointer){.cdecl,
  348. dynlib: DLLUtilName, importc.}
  349. proc allocWrapper(size: int): pointer {.cdecl.} = allocShared(size)
  350. proc reallocWrapper(p: pointer; newsize: int): pointer {.cdecl.} =
  351. if p == nil:
  352. if newSize > 0: result = allocShared(newsize)
  353. elif newsize == 0: deallocShared(p)
  354. else: result = reallocShared(p, newsize)
  355. proc deallocWrapper(p: pointer) {.cdecl.} =
  356. if p != nil: deallocShared(p)
  357. proc CRYPTO_malloc_init*() =
  358. when not useWinVersion and not defined(macosx) and not defined(android) and not defined(nimNoAllocForSSL):
  359. CRYPTO_set_mem_functions(allocWrapper, reallocWrapper, deallocWrapper)
  360. proc SSL_CTX_ctrl*(ctx: SslCtx, cmd: cInt, larg: int, parg: pointer): int{.
  361. cdecl, dynlib: DLLSSLName, importc.}
  362. proc SSL_CTX_callback_ctrl(ctx: SslCtx, typ: cInt, fp: PFunction): int{.
  363. cdecl, dynlib: DLLSSLName, importc.}
  364. proc SSLCTXSetMode*(ctx: SslCtx, mode: int): int =
  365. result = SSL_CTX_ctrl(ctx, SSL_CTRL_MODE, mode, nil)
  366. proc SSL_ctrl*(ssl: SslPtr, cmd: cInt, larg: int, parg: pointer): int{.
  367. cdecl, dynlib: DLLSSLName, importc.}
  368. proc SSL_set_tlsext_host_name*(ssl: SslPtr, name: cstring): int =
  369. result = SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name, name)
  370. ## Set the SNI server name extension to be used in a client hello.
  371. ## Returns 1 if SNI was set, 0 if current SSL configuration doesn't support SNI.
  372. proc SSL_get_servername*(ssl: SslPtr, typ: cInt = TLSEXT_NAMETYPE_host_name): cstring {.cdecl, dynlib: DLLSSLName, importc.}
  373. ## Retrieve the server name requested in the client hello. This can be used
  374. ## in the callback set in `SSL_CTX_set_tlsext_servername_callback` to
  375. ## implement virtual hosting. May return `nil`.
  376. proc SSL_CTX_set_tlsext_servername_callback*(ctx: SslCtx, cb: proc(ssl: SslPtr, cb_id: int, arg: pointer): int {.cdecl.}): int =
  377. ## Set the callback to be used on listening SSL connections when the client hello is received.
  378. ##
  379. ## The callback should return one of:
  380. ## * SSL_TLSEXT_ERR_OK
  381. ## * SSL_TLSEXT_ERR_ALERT_WARNING
  382. ## * SSL_TLSEXT_ERR_ALERT_FATAL
  383. ## * SSL_TLSEXT_ERR_NOACK
  384. result = SSL_CTX_callback_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, cast[PFunction](cb))
  385. proc SSL_CTX_set_tlsext_servername_arg*(ctx: SslCtx, arg: pointer): int =
  386. ## Set the pointer to be used in the callback registered to ``SSL_CTX_set_tlsext_servername_callback``.
  387. result = SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, arg)
  388. type
  389. PskClientCallback* = proc (ssl: SslPtr;
  390. hint: cstring; identity: cstring; max_identity_len: cuint; psk: ptr cuchar;
  391. max_psk_len: cuint): cuint {.cdecl.}
  392. PskServerCallback* = proc (ssl: SslPtr;
  393. identity: cstring; psk: ptr cuchar; max_psk_len: cint): cuint {.cdecl.}
  394. proc SSL_CTX_set_psk_client_callback*(ctx: SslCtx; callback: PskClientCallback) {.cdecl, dynlib: DLLSSLName, importc.}
  395. ## Set callback called when OpenSSL needs PSK (for client).
  396. proc SSL_CTX_set_psk_server_callback*(ctx: SslCtx; callback: PskServerCallback) {.cdecl, dynlib: DLLSSLName, importc.}
  397. ## Set callback called when OpenSSL needs PSK (for server).
  398. proc SSL_CTX_use_psk_identity_hint*(ctx: SslCtx; hint: cstring): cint {.cdecl, dynlib: DLLSSLName, importc.}
  399. ## Set PSK identity hint to use.
  400. proc SSL_get_psk_identity*(ssl: SslPtr): cstring {.cdecl, dynlib: DLLSSLName, importc.}
  401. ## Get PSK identity.
  402. proc bioNew*(b: PBIO_METHOD): BIO{.cdecl, dynlib: DLLUtilName, importc: "BIO_new".}
  403. proc bioFreeAll*(b: BIO){.cdecl, dynlib: DLLUtilName, importc: "BIO_free_all".}
  404. proc bioSMem*(): PBIO_METHOD{.cdecl, dynlib: DLLUtilName, importc: "BIO_s_mem".}
  405. proc bioCtrlPending*(b: BIO): cInt{.cdecl, dynlib: DLLUtilName, importc: "BIO_ctrl_pending".}
  406. proc bioRead*(b: BIO, Buf: cstring, length: cInt): cInt{.cdecl,
  407. dynlib: DLLUtilName, importc: "BIO_read".}
  408. proc bioWrite*(b: BIO, Buf: cstring, length: cInt): cInt{.cdecl,
  409. dynlib: DLLUtilName, importc: "BIO_write".}
  410. proc sslSetConnectState*(s: SslPtr) {.cdecl,
  411. dynlib: DLLSSLName, importc: "SSL_set_connect_state".}
  412. proc sslSetAcceptState*(s: SslPtr) {.cdecl,
  413. dynlib: DLLSSLName, importc: "SSL_set_accept_state".}
  414. proc sslRead*(ssl: SslPtr, buf: cstring, num: cInt): cInt{.cdecl,
  415. dynlib: DLLSSLName, importc: "SSL_read".}
  416. proc sslPeek*(ssl: SslPtr, buf: cstring, num: cInt): cInt{.cdecl,
  417. dynlib: DLLSSLName, importc: "SSL_peek".}
  418. proc sslWrite*(ssl: SslPtr, buf: cstring, num: cInt): cInt{.cdecl,
  419. dynlib: DLLSSLName, importc: "SSL_write".}
  420. proc sslSetBio*(ssl: SslPtr, rbio, wbio: BIO) {.cdecl,
  421. dynlib: DLLSSLName, importc: "SSL_set_bio".}
  422. proc sslDoHandshake*(ssl: SslPtr): cint {.cdecl,
  423. dynlib: DLLSSLName, importc: "SSL_do_handshake".}
  424. proc ErrClearError*(){.cdecl, dynlib: DLLUtilName, importc: "ERR_clear_error".}
  425. proc ErrFreeStrings*(){.cdecl, dynlib: DLLUtilName, importc: "ERR_free_strings".}
  426. proc ErrRemoveState*(pid: cInt){.cdecl, dynlib: DLLUtilName, importc: "ERR_remove_state".}
  427. proc PEM_read_bio_RSA_PUBKEY*(bp: BIO, x: ptr PRSA, pw: pem_password_cb, u: pointer): PRSA {.cdecl,
  428. dynlib: DLLSSLName, importc.}
  429. proc RSA_verify*(kind: cint, origMsg: pointer, origMsgLen: cuint, signature: pointer,
  430. signatureLen: cuint, rsa: PRSA): cint {.cdecl, dynlib: DLLSSLName, importc.}
  431. when true:
  432. discard
  433. else:
  434. proc SslCtxSetCipherList*(arg0: PSSL_CTX, str: cstring): cInt{.cdecl,
  435. dynlib: DLLSSLName, importc.}
  436. proc SslCtxNew*(meth: PSSL_METHOD): PSSL_CTX{.cdecl,
  437. dynlib: DLLSSLName, importc.}
  438. proc SslSetFd*(s: PSSL, fd: cInt): cInt{.cdecl, dynlib: DLLSSLName, importc.}
  439. proc SslCTXCtrl*(ctx: PSSL_CTX, cmd: cInt, larg: int, parg: Pointer): int{.
  440. cdecl, dynlib: DLLSSLName, importc.}
  441. proc SSLSetMode*(s: PSSL, mode: int): int
  442. proc SSLCTXGetMode*(ctx: PSSL_CTX): int
  443. proc SSLGetMode*(s: PSSL): int
  444. proc SslMethodV2*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.}
  445. proc SslMethodV3*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.}
  446. proc SslMethodTLSV1*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.}
  447. proc SslMethodV23*(): PSSL_METHOD{.cdecl, dynlib: DLLSSLName, importc.}
  448. proc SslCtxUsePrivateKey*(ctx: PSSL_CTX, pkey: SslPtr): cInt{.cdecl,
  449. dynlib: DLLSSLName, importc.}
  450. proc SslCtxUsePrivateKeyASN1*(pk: cInt, ctx: PSSL_CTX,
  451. d: cstring, length: int): cInt{.cdecl, dynlib: DLLSSLName, importc.}
  452. proc SslCtxUseCertificate*(ctx: PSSL_CTX, x: SslPtr): cInt{.cdecl,
  453. dynlib: DLLSSLName, importc.}
  454. proc SslCtxUseCertificateASN1*(ctx: PSSL_CTX, length: int, d: cstring): cInt{.
  455. cdecl, dynlib: DLLSSLName, importc.}
  456. # function SslCtxUseCertificateChainFile(ctx: PSSL_CTX; const filename: PChar):cInt;
  457. proc SslCtxUseCertificateChainFile*(ctx: PSSL_CTX, filename: cstring): cInt{.
  458. cdecl, dynlib: DLLSSLName, importc.}
  459. proc SslCtxSetDefaultPasswdCb*(ctx: PSSL_CTX, cb: PPasswdCb){.cdecl,
  460. dynlib: DLLSSLName, importc.}
  461. proc SslCtxSetDefaultPasswdCbUserdata*(ctx: PSSL_CTX, u: SslPtr){.cdecl,
  462. dynlib: DLLSSLName, importc.}
  463. # function SslCtxLoadVerifyLocations(ctx: PSSL_CTX; const CAfile: PChar; const CApath: PChar):cInt;
  464. proc SslCtxLoadVerifyLocations*(ctx: PSSL_CTX, CAfile: cstring, CApath: cstring): cInt{.
  465. cdecl, dynlib: DLLSSLName, importc.}
  466. proc SslNew*(ctx: PSSL_CTX): PSSL{.cdecl, dynlib: DLLSSLName, importc.}
  467. proc SslConnect*(ssl: PSSL): cInt{.cdecl, dynlib: DLLSSLName, importc.}
  468. proc SslGetVersion*(ssl: PSSL): cstring{.cdecl, dynlib: DLLSSLName, importc.}
  469. proc SslGetPeerCertificate*(ssl: PSSL): PX509{.cdecl, dynlib: DLLSSLName,
  470. importc.}
  471. proc SslCtxSetVerify*(ctx: PSSL_CTX, mode: cInt, arg2: PFunction){.cdecl,
  472. dynlib: DLLSSLName, importc.}
  473. proc SSLGetCurrentCipher*(s: PSSL): SslPtr{.cdecl, dynlib: DLLSSLName, importc.}
  474. proc SSLCipherGetName*(c: SslPtr): cstring{.cdecl, dynlib: DLLSSLName, importc.}
  475. proc SSLCipherGetBits*(c: SslPtr, alg_bits: var cInt): cInt{.cdecl,
  476. dynlib: DLLSSLName, importc.}
  477. proc SSLGetVerifyResult*(ssl: PSSL): int{.cdecl, dynlib: DLLSSLName, importc.}
  478. # libeay.dll
  479. proc X509New*(): PX509{.cdecl, dynlib: DLLUtilName, importc.}
  480. proc X509Free*(x: PX509){.cdecl, dynlib: DLLUtilName, importc.}
  481. proc X509NameOneline*(a: PX509_NAME, buf: cstring, size: cInt): cstring{.
  482. cdecl, dynlib: DLLUtilName, importc.}
  483. proc X509GetSubjectName*(a: PX509): PX509_NAME{.cdecl, dynlib: DLLUtilName,
  484. importc.}
  485. proc X509GetIssuerName*(a: PX509): PX509_NAME{.cdecl, dynlib: DLLUtilName,
  486. importc.}
  487. proc X509NameHash*(x: PX509_NAME): int{.cdecl, dynlib: DLLUtilName, importc.}
  488. # function SslX509Digest(data: PX509; typ: PEVP_MD; md: PChar; len: PcInt):cInt;
  489. proc X509Digest*(data: PX509, typ: PEVP_MD, md: cstring, length: var cInt): cInt{.
  490. cdecl, dynlib: DLLUtilName, importc.}
  491. proc X509print*(b: PBIO, a: PX509): cInt{.cdecl, dynlib: DLLUtilName, importc.}
  492. proc X509SetVersion*(x: PX509, version: cInt): cInt{.cdecl, dynlib: DLLUtilName,
  493. importc.}
  494. proc X509SetPubkey*(x: PX509, pkey: EVP_PKEY): cInt{.cdecl, dynlib: DLLUtilName,
  495. importc.}
  496. proc X509SetIssuerName*(x: PX509, name: PX509_NAME): cInt{.cdecl,
  497. dynlib: DLLUtilName, importc.}
  498. proc X509NameAddEntryByTxt*(name: PX509_NAME, field: cstring, typ: cInt,
  499. bytes: cstring, length, loc, theSet: cInt): cInt{.
  500. cdecl, dynlib: DLLUtilName, importc.}
  501. proc X509Sign*(x: PX509, pkey: EVP_PKEY, md: PEVP_MD): cInt{.cdecl,
  502. dynlib: DLLUtilName, importc.}
  503. proc X509GmtimeAdj*(s: PASN1_UTCTIME, adj: cInt): PASN1_UTCTIME{.cdecl,
  504. dynlib: DLLUtilName, importc.}
  505. proc X509SetNotBefore*(x: PX509, tm: PASN1_UTCTIME): cInt{.cdecl,
  506. dynlib: DLLUtilName, importc.}
  507. proc X509SetNotAfter*(x: PX509, tm: PASN1_UTCTIME): cInt{.cdecl,
  508. dynlib: DLLUtilName, importc.}
  509. proc X509GetSerialNumber*(x: PX509): PASN1_cInt{.cdecl, dynlib: DLLUtilName,
  510. importc.}
  511. proc EvpPkeyNew*(): EVP_PKEY{.cdecl, dynlib: DLLUtilName, importc.}
  512. proc EvpPkeyFree*(pk: EVP_PKEY){.cdecl, dynlib: DLLUtilName, importc.}
  513. proc EvpPkeyAssign*(pkey: EVP_PKEY, typ: cInt, key: Prsa): cInt{.cdecl,
  514. dynlib: DLLUtilName, importc.}
  515. proc EvpGetDigestByName*(Name: cstring): PEVP_MD{.cdecl, dynlib: DLLUtilName,
  516. importc.}
  517. proc EVPcleanup*(){.cdecl, dynlib: DLLUtilName, importc.}
  518. # function ErrErrorString(e: cInt; buf: PChar): PChar;
  519. proc SSLeayversion*(t: cInt): cstring{.cdecl, dynlib: DLLUtilName, importc.}
  520. proc OPENSSLaddallalgorithms*(){.cdecl, dynlib: DLLUtilName, importc.}
  521. proc CRYPTOcleanupAllExData*(){.cdecl, dynlib: DLLUtilName, importc.}
  522. proc RandScreen*(){.cdecl, dynlib: DLLUtilName, importc.}
  523. proc d2iPKCS12bio*(b: PBIO, Pkcs12: SslPtr): SslPtr{.cdecl, dynlib: DLLUtilName,
  524. importc.}
  525. proc PKCS12parse*(p12: SslPtr, pass: cstring, pkey, cert, ca: var SslPtr): cint{.
  526. dynlib: DLLUtilName, importc, cdecl.}
  527. proc PKCS12free*(p12: SslPtr){.cdecl, dynlib: DLLUtilName, importc.}
  528. proc RsaGenerateKey*(bits, e: cInt, callback: PFunction, cb_arg: SslPtr): PRSA{.
  529. cdecl, dynlib: DLLUtilName, importc.}
  530. proc Asn1UtctimeNew*(): PASN1_UTCTIME{.cdecl, dynlib: DLLUtilName, importc.}
  531. proc Asn1UtctimeFree*(a: PASN1_UTCTIME){.cdecl, dynlib: DLLUtilName, importc.}
  532. proc Asn1cIntSet*(a: PASN1_cInt, v: cInt): cInt{.cdecl, dynlib: DLLUtilName,
  533. importc.}
  534. proc i2dX509bio*(b: PBIO, x: PX509): cInt{.cdecl, dynlib: DLLUtilName, importc.}
  535. proc i2dPrivateKeyBio*(b: PBIO, pkey: EVP_PKEY): cInt{.cdecl,
  536. dynlib: DLLUtilName, importc.}
  537. # 3DES functions
  538. proc DESsetoddparity*(Key: des_cblock){.cdecl, dynlib: DLLUtilName, importc.}
  539. proc DESsetkeychecked*(key: des_cblock, schedule: des_key_schedule): cInt{.
  540. cdecl, dynlib: DLLUtilName, importc.}
  541. proc DESecbencrypt*(Input: des_cblock, output: des_cblock, ks: des_key_schedule,
  542. enc: cInt){.cdecl, dynlib: DLLUtilName, importc.}
  543. # implementation
  544. proc SSLSetMode(s: PSSL, mode: int): int =
  545. result = SSLctrl(s, SSL_CTRL_MODE, mode, nil)
  546. proc SSLCTXGetMode(ctx: PSSL_CTX): int =
  547. result = SSLCTXctrl(ctx, SSL_CTRL_MODE, 0, nil)
  548. proc SSLGetMode(s: PSSL): int =
  549. result = SSLctrl(s, SSL_CTRL_MODE, 0, nil)
  550. # <openssl/md5.h>
  551. type
  552. MD5_LONG* = cuint
  553. const
  554. MD5_CBLOCK* = 64
  555. MD5_LBLOCK* = int(MD5_CBLOCK div 4)
  556. MD5_DIGEST_LENGTH* = 16
  557. type
  558. MD5_CTX* = object
  559. A,B,C,D,Nl,Nh: MD5_LONG
  560. data: array[MD5_LBLOCK, MD5_LONG]
  561. num: cuint
  562. {.push callconv:cdecl, dynlib:DLLUtilName.}
  563. proc md5_Init*(c: var MD5_CTX): cint{.importc: "MD5_Init".}
  564. proc md5_Update*(c: var MD5_CTX; data: pointer; len: csize): cint{.importc: "MD5_Update".}
  565. proc md5_Final*(md: cstring; c: var MD5_CTX): cint{.importc: "MD5_Final".}
  566. proc md5*(d: ptr cuchar; n: csize; md: ptr cuchar): ptr cuchar{.importc: "MD5".}
  567. proc md5_Transform*(c: var MD5_CTX; b: ptr cuchar){.importc: "MD5_Transform".}
  568. {.pop.}
  569. from strutils import toHex, toLowerAscii
  570. proc hexStr(buf: cstring): string =
  571. # turn md5s output into a nice hex str
  572. result = newStringOfCap(32)
  573. for i in 0 ..< 16:
  574. result.add toHex(buf[i].ord, 2).toLowerAscii
  575. proc md5_File*(file: string): string {.raises: [IOError,Exception].} =
  576. ## Generate MD5 hash for a file. Result is a 32 character
  577. # hex string with lowercase characters (like the output
  578. # of `md5sum`
  579. const
  580. sz = 512
  581. let f = open(file,fmRead)
  582. var
  583. buf: array[sz,char]
  584. ctx: MD5_CTX
  585. discard md5_init(ctx)
  586. while(let bytes = f.readChars(buf, 0, sz); bytes > 0):
  587. discard md5_update(ctx, buf[0].addr, bytes)
  588. discard md5_final(buf[0].addr, ctx)
  589. f.close
  590. result = hexStr(addr buf)
  591. proc md5_Str*(str: string): string =
  592. ## Generate MD5 hash for a string. Result is a 32 character
  593. ## hex string with lowercase characters
  594. var
  595. ctx: MD5_CTX
  596. res: array[MD5_DIGEST_LENGTH,char]
  597. input = str.cstring
  598. discard md5_init(ctx)
  599. var i = 0
  600. while i < str.len:
  601. let L = min(str.len - i, 512)
  602. discard md5_update(ctx, input[i].addr, L)
  603. i += L
  604. discard md5_final(addr res, ctx)
  605. result = hexStr(addr res)