Is this pairing scheme for establishing trust between two devices with self-signed TLS certs secure from MITM? Assume two devices (A and B) with self-signed TLS certificates (this part can't change). We want these devices to trust each other.

One way to do this is to simply copy A's cert over to B's allowed cert list and vice versa, but this is a little cumbersome usability-wise.

Instead, what about this scheme:


Device A generates a key K that it remembers for a short period of time
The user copies K and enters it in, along with device A's hostname, on device B
Device B makes a TLS connection to device A and includes its client cert
Device B sends message m1 = HMAC(K, "request" + its client cert + observed server cert)
Device A checks that m1 looks like what it expects, if not, it closes the connection
Device A responds with m2 = HMAC(K, "response" + observed client cert + its server cert) and adds device B's cert to its trusted list
Device B checks that m2 looks correct, and if so, adds device A's cert to its trusted list.


Is this secure, and if so, how short can K be?
This is fine.  There is one corner case I would note which is that the message from 4 can be replayed in 6.  So the authenticated messages should include an indication of whether they are for step 4 or 6.  As for how short K can be: as long as necessary to get the guarantee you want from HMAC.