emqx_tls_lib_tests.erl 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. %%--------------------------------------------------------------------
  2. %% Copyright (c) 2021-2023 EMQ Technologies Co., Ltd. All Rights Reserved.
  3. %%
  4. %% Licensed under the Apache License, Version 2.0 (the "License");
  5. %% you may not use this file except in compliance with the License.
  6. %% You may obtain a copy of the License at
  7. %%
  8. %% http://www.apache.org/licenses/LICENSE-2.0
  9. %%
  10. %% Unless required by applicable law or agreed to in writing, software
  11. %% distributed under the License is distributed on an "AS IS" BASIS,
  12. %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. %% See the License for the specific language governing permissions and
  14. %% limitations under the License.
  15. %%--------------------------------------------------------------------
  16. -module(emqx_tls_lib_tests).
  17. -include_lib("eunit/include/eunit.hrl").
  18. %% one of the cipher suite from tlsv1.2 and tlsv1.3 each
  19. -define(TLS_12_CIPHER, "ECDHE-ECDSA-AES256-GCM-SHA384").
  20. -define(TLS_13_CIPHER, "TLS_AES_256_GCM_SHA384").
  21. ensure_tls13_ciphers_added_test() ->
  22. Ciphers = emqx_tls_lib:integral_ciphers(['tlsv1.3'], [?TLS_12_CIPHER]),
  23. ?assert(lists:member(?TLS_12_CIPHER, Ciphers)),
  24. ?assert(lists:member(?TLS_13_CIPHER, Ciphers)).
  25. legacy_cipher_suites_test() ->
  26. Ciphers = emqx_tls_lib:integral_ciphers(['tlsv1.2'], [?TLS_12_CIPHER]),
  27. ?assertEqual([?TLS_12_CIPHER], Ciphers).
  28. use_default_ciphers_test() ->
  29. Ciphers = emqx_tls_lib:integral_ciphers(['tlsv1.3', 'tlsv1.2'], ""),
  30. ?assert(lists:member(?TLS_12_CIPHER, Ciphers)),
  31. ?assert(lists:member(?TLS_13_CIPHER, Ciphers)).
  32. ciphers_format_test_() ->
  33. String = ?TLS_13_CIPHER ++ "," ++ ?TLS_12_CIPHER,
  34. Binary = bin(String),
  35. List = [?TLS_13_CIPHER, ?TLS_12_CIPHER],
  36. [
  37. {"string", fun() -> test_cipher_format(String) end},
  38. {"binary", fun() -> test_cipher_format(Binary) end},
  39. {"string-list", fun() -> test_cipher_format(List) end}
  40. ].
  41. test_cipher_format(Input) ->
  42. Ciphers = emqx_tls_lib:integral_ciphers(['tlsv1.3', 'tlsv1.2'], Input),
  43. ?assertEqual([?TLS_13_CIPHER, ?TLS_12_CIPHER], Ciphers).
  44. tls_versions_test() ->
  45. ?assert(lists:member('tlsv1.3', emqx_tls_lib:available_versions(tls))).
  46. tls_version_unknown_test_() ->
  47. lists:flatmap(
  48. fun(Type) ->
  49. [
  50. ?_assertEqual(
  51. emqx_tls_lib:available_versions(Type),
  52. emqx_tls_lib:integral_versions(Type, [])
  53. ),
  54. ?_assertEqual(
  55. emqx_tls_lib:available_versions(Type),
  56. emqx_tls_lib:integral_versions(Type, <<>>)
  57. ),
  58. ?_assertEqual(
  59. emqx_tls_lib:available_versions(Type),
  60. %% unknown version dropped
  61. emqx_tls_lib:integral_versions(Type, "foo")
  62. ),
  63. fun() ->
  64. ?assertError(
  65. #{reason := no_available_tls_version},
  66. emqx_tls_lib:integral_versions(Type, [foo])
  67. )
  68. end
  69. ]
  70. end,
  71. [tls, dtls]
  72. ).
  73. cipher_suites_no_duplication_test() ->
  74. AllCiphers = emqx_tls_lib:default_ciphers(),
  75. ?assertEqual(length(AllCiphers), length(lists:usort(AllCiphers))).
  76. ssl_files_failure_test_() ->
  77. [
  78. {"undefined_is_undefined", fun() ->
  79. ?assertEqual(
  80. {ok, undefined},
  81. emqx_tls_lib:ensure_ssl_files("dir", undefined)
  82. )
  83. end},
  84. {"no_op_if_disabled", fun() ->
  85. Disabled = #{<<"enable">> => false, foo => bar},
  86. ?assertEqual(
  87. {ok, Disabled},
  88. emqx_tls_lib:ensure_ssl_files("dir", Disabled)
  89. )
  90. end},
  91. {"enoent_key_file", fun() ->
  92. NonExistingFile = filename:join(
  93. "/tmp", integer_to_list(erlang:system_time(microsecond))
  94. ),
  95. ?assertMatch(
  96. {error, #{file_read := enoent, pem_check := invalid_pem}},
  97. emqx_tls_lib:ensure_ssl_files("/tmp", #{
  98. <<"keyfile">> => NonExistingFile,
  99. <<"certfile">> => test_key(),
  100. <<"cacertfile">> => test_key()
  101. })
  102. )
  103. end},
  104. {"bad_pem_string", fun() ->
  105. %% empty string
  106. ?assertMatch(
  107. {error, #{
  108. reason := invalid_file_path_or_pem_string, which_options := [[<<"keyfile">>]]
  109. }},
  110. emqx_tls_lib:ensure_ssl_files("/tmp", #{
  111. <<"keyfile">> => <<>>,
  112. <<"certfile">> => test_key(),
  113. <<"cacertfile">> => test_key()
  114. })
  115. ),
  116. %% not valid unicode
  117. ?assertMatch(
  118. {error, #{
  119. reason := invalid_file_path_or_pem_string, which_options := [[<<"keyfile">>]]
  120. }},
  121. emqx_tls_lib:ensure_ssl_files("/tmp", #{
  122. <<"keyfile">> => <<255, 255>>,
  123. <<"certfile">> => test_key(),
  124. <<"cacertfile">> => test_key()
  125. })
  126. ),
  127. ?assertMatch(
  128. {error, #{
  129. reason := invalid_file_path_or_pem_string,
  130. which_options := [[<<"ocsp">>, <<"issuer_pem">>]]
  131. }},
  132. emqx_tls_lib:ensure_ssl_files("/tmp", #{
  133. <<"keyfile">> => test_key(),
  134. <<"certfile">> => test_key(),
  135. <<"cacertfile">> => test_key(),
  136. <<"ocsp">> => #{<<"issuer_pem">> => <<255, 255>>}
  137. })
  138. ),
  139. %% not printable
  140. ?assertMatch(
  141. {error, #{reason := invalid_file_path_or_pem_string}},
  142. emqx_tls_lib:ensure_ssl_files("/tmp", #{
  143. <<"keyfile">> => <<33, 22>>,
  144. <<"certfile">> => test_key(),
  145. <<"cacertfile">> => test_key()
  146. })
  147. ),
  148. TmpFile = filename:join("/tmp", integer_to_list(erlang:system_time(microsecond))),
  149. try
  150. ok = file:write_file(TmpFile, <<"not a valid pem">>),
  151. ?assertMatch(
  152. {error, #{file_read := not_pem}},
  153. emqx_tls_lib:ensure_ssl_files(
  154. "/tmp",
  155. #{
  156. <<"cacertfile">> => bin(TmpFile),
  157. <<"keyfile">> => bin(TmpFile),
  158. <<"certfile">> => bin(TmpFile),
  159. <<"ocsp">> => #{<<"issuer_pem">> => bin(TmpFile)}
  160. }
  161. )
  162. )
  163. after
  164. file:delete(TmpFile)
  165. end
  166. end}
  167. ].
  168. ssl_file_replace_test() ->
  169. Key1 = test_key(),
  170. Key2 = test_key2(),
  171. SSL0 = #{
  172. <<"keyfile">> => Key1,
  173. <<"certfile">> => Key1,
  174. <<"cacertfile">> => Key1,
  175. <<"ocsp">> => #{<<"issuer_pem">> => Key1}
  176. },
  177. SSL1 = #{
  178. <<"keyfile">> => Key2,
  179. <<"certfile">> => Key2,
  180. <<"cacertfile">> => Key2,
  181. <<"ocsp">> => #{<<"issuer_pem">> => Key2}
  182. },
  183. Dir = filename:join(["/tmp", "ssl-test-dir2"]),
  184. {ok, SSL2} = emqx_tls_lib:ensure_ssl_files(Dir, SSL0),
  185. {ok, SSL3} = emqx_tls_lib:ensure_ssl_files(Dir, SSL1),
  186. File1 = maps:get(<<"keyfile">>, SSL2),
  187. File2 = maps:get(<<"keyfile">>, SSL3),
  188. IssuerPem1 = emqx_utils_maps:deep_get([<<"ocsp">>, <<"issuer_pem">>], SSL2),
  189. IssuerPem2 = emqx_utils_maps:deep_get([<<"ocsp">>, <<"issuer_pem">>], SSL3),
  190. ?assert(filelib:is_regular(File1)),
  191. ?assert(filelib:is_regular(File2)),
  192. ?assert(filelib:is_regular(IssuerPem1)),
  193. ?assert(filelib:is_regular(IssuerPem2)),
  194. ok.
  195. ssl_file_deterministic_names_test() ->
  196. SSL0 = #{
  197. <<"keyfile">> => test_key(),
  198. <<"certfile">> => test_key()
  199. },
  200. Dir0 = filename:join(["/tmp", ?FUNCTION_NAME, "ssl0"]),
  201. Dir1 = filename:join(["/tmp", ?FUNCTION_NAME, "ssl1"]),
  202. {ok, SSLFiles0} = emqx_tls_lib:ensure_ssl_files(Dir0, SSL0),
  203. ?assertEqual(
  204. {ok, SSLFiles0},
  205. emqx_tls_lib:ensure_ssl_files(Dir0, SSL0)
  206. ),
  207. ?assertNotEqual(
  208. {ok, SSLFiles0},
  209. emqx_tls_lib:ensure_ssl_files(Dir1, SSL0)
  210. ),
  211. _ = file:del_dir_r(filename:join(["/tmp", ?FUNCTION_NAME])).
  212. to_client_opts_test() ->
  213. VersionsAll = [tlsv1, 'tlsv1.1', 'tlsv1.2', 'tlsv1.3'],
  214. Versions13Only = ['tlsv1.3'],
  215. Options = #{
  216. enable => true,
  217. verify => "Verify",
  218. server_name_indication => "SNI",
  219. ciphers => "Ciphers",
  220. depth => "depth",
  221. password => "password",
  222. versions => VersionsAll,
  223. secure_renegotiate => "secure_renegotiate",
  224. reuse_sessions => "reuse_sessions"
  225. },
  226. Expected1 = lists:usort(maps:keys(Options) -- [enable]),
  227. ?assertEqual(
  228. Expected1, lists:usort(proplists:get_keys(emqx_tls_lib:to_client_opts(tls, Options)))
  229. ),
  230. Expected2 =
  231. lists:usort(
  232. maps:keys(Options) --
  233. [enable, reuse_sessions, secure_renegotiate]
  234. ),
  235. ?assertEqual(
  236. Expected2,
  237. lists:usort(
  238. proplists:get_keys(
  239. emqx_tls_lib:to_client_opts(tls, Options#{versions := Versions13Only})
  240. )
  241. )
  242. ),
  243. Expected3 = lists:usort(maps:keys(Options) -- [enable, depth, password]),
  244. ?assertEqual(
  245. Expected3,
  246. lists:usort(
  247. proplists:get_keys(
  248. emqx_tls_lib:to_client_opts(tls, Options#{depth := undefined, password := ""})
  249. )
  250. )
  251. ).
  252. to_server_opts_test() ->
  253. VersionsAll = [tlsv1, 'tlsv1.1', 'tlsv1.2', 'tlsv1.3'],
  254. Versions13Only = ['tlsv1.3'],
  255. Options = #{
  256. verify => "Verify",
  257. ciphers => "Ciphers",
  258. versions => VersionsAll,
  259. user_lookup_fun => "funfunfun",
  260. client_renegotiation => "client_renegotiation"
  261. },
  262. Expected1 = lists:usort(maps:keys(Options)),
  263. ?assertEqual(
  264. Expected1, lists:usort(proplists:get_keys(emqx_tls_lib:to_server_opts(tls, Options)))
  265. ),
  266. Expected2 = lists:usort(maps:keys(Options) -- [user_lookup_fun, client_renegotiation]),
  267. ?assertEqual(
  268. Expected2,
  269. lists:usort(
  270. proplists:get_keys(
  271. emqx_tls_lib:to_server_opts(tls, Options#{versions := Versions13Only})
  272. )
  273. )
  274. ).
  275. bin(X) -> iolist_to_binary(X).
  276. test_key() ->
  277. <<
  278. "\n"
  279. "-----BEGIN EC PRIVATE KEY-----\n"
  280. "MHQCAQEEICKTbbathzvD8zvgjL7qRHhW4alS0+j0Loo7WeYX9AxaoAcGBSuBBAAK\n"
  281. "oUQDQgAEJBdF7MIdam5T4YF3JkEyaPKdG64TVWCHwr/plC0QzNVJ67efXwxlVGTo\n"
  282. "ju0VBj6tOX1y6C0U+85VOM0UU5xqvw==\n"
  283. "-----END EC PRIVATE KEY-----\n"
  284. >>.
  285. test_key2() ->
  286. <<
  287. "\n"
  288. "-----BEGIN EC PRIVATE KEY-----\n"
  289. "MHQCAQEEID9UlIyAlLFw0irkRHX29N+ZGivGtDjlVJvATY3B0TTmoAcGBSuBBAAK\n"
  290. "oUQDQgAEUwiarudRNAT25X11js8gE9G+q0GdsT53QJQjRtBO+rTwuCW1vhLzN0Ve\n"
  291. "AbToUD4JmV9m/XwcSVH06ZaWqNuC5w==\n"
  292. "-----END EC PRIVATE KEY-----\n"
  293. >>.