mtrudel / hap

A HomeKit Accessory Protocol (HAP) Implementation for Elixir
MIT License
90 stars 9 forks source link

Fix ChaCha20 encryption for newer OpenSSL versions #127

Closed kamilwaz closed 4 months ago

kamilwaz commented 4 months ago

The newer OpenSSL versions do not pad the nonce with zeros to make them 12 bytes long which causes the following error:

15:47:07.324 [error] GenServer HAP.PairSetup terminating
** (stop) {:badarg, {~c"aead.c", 111}, ~c"Bad IV length"}
    (crypto 5.4.2) crypto.erl:1023: :crypto.crypto_one_time_aead(:chacha20_poly1305, <<8, 242, 184, 237, 202, 96, 139, 82, 175, 153, 130, 188, 214, 69, 45, 206, 136, 191, 202, 212, 157, 82, 43, 80, 178, 117, 120, 195, 67, 199, 155, 82>>, "PS-Msg05", <<126, 129, 219, 117, 130, 252, 108, 219, 177, 67, 226, 238, 183, 82, 11, 198, 249, 206, 184, 58, 253, 99, 250, 96, 241, 48, 55, 137, 8, 4, 44, 221, 90, 89, 164, 229, 85, 46, 27, 138, 139, 116, 248, 89, 81, 102, 66, 2, 217, 243, ...>>, "", <<158, 19, 97, 139, 209, 177, 128, 185, 192, 165, 200, 111, 63, 106, 25, 111>>, false)
    (hap 0.4.9) lib/hap/crypto/cha_cha_20.ex:24: HAP.Crypto.ChaCha20.decrypt_and_verify/4
    (hap 0.4.9) lib/hap/pair_setup.ex:97: HAP.PairSetup.handle_call/3
    (stdlib 5.2.2) gen_server.erl:1131: :gen_server.try_handle_call/4
    (stdlib 5.2.2) gen_server.erl:1160: :gen_server.handle_msg/6
    (stdlib 5.2.2) proc_lib.erl:241: :proc_lib.init_p_do_apply/3
Last message (from #PID<0.889.0>): %{5 => <<126, 129, 219, 117, 130, 252, 108, 219, 177, 67, 226, 238, 183, 82, 11, 198, 249, 206, 184, 58, 253, 99, 250, 96, 241, 48, 55, 137, 8, 4, 44, 221, 90, 89, 164, 229, 85, 46, 27, 138, 139, 116, 248, 89, 81, 102, 66, 2, 217, ...>>, 6 => <<5>>}
State: %{step: 5, session_key: <<59, 161, 16, 19, 236, 194, 48, 122, 60, 103, 146, 15, 5, 33, 139, 255, 88, 205, 107, 76, 232, 25, 49, 61, 109, 208, 65, 108, 14, 133, 249, 120, 71, 104, 19, 28, 53, 116, 156, 246, 217, 240, 217, 8, 65, 62, 150, 29, ...>>}
Client #PID<0.889.0> is alive

This PR fixes the issue by always padding the nonce to the required size.

mtrudel commented 4 months ago

Thanks for this - the amount of flux in OTP's crypto libraries lately has been frustrating to say the least (it's not AT ALL their fault; the upstream move to OpenSSL 3.x is the ultimate cause).