blib/lib/Protocol/HAP/Pairing.pm

filter: Statementstmt 16.6% 30 / 180 Branchbran 0.0% 0 / 50 Conditioncond 9.5% 2 / 21 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 43.4% 10 / 23 Podpod 0.0% 0 / 6 totaltotal 14.3% 42 / 292 CC 36 SCAR 33.1
CC
36
Cov
13%
handle_pair_setup
72.0
_pair_setup_m1_m2
56.0
clear_pairing_state
30.0
CRAP 27.3
« blib/lib/Protocol/HAP/Server.pm ↑ Summary blib/lib/Protocol/HAP/Session.pm »
1 1 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
2  
3 package Protocol::HAP::Pairing;
4 1 our $VERSION = '0.1.0';
5  
6 1 ▶use Protocol::HAP;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Protocol::HAP::TLV;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use Protocol::HAP::SRP;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Protocol::HAP::Crypto;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 1 ▶use Protocol::HAP::SetupCode qw(normalize_setup_code);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 # TLV Types for pairing
14 1 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 kTLVType_Method => 0x00,
16 kTLVType_Identifier => 0x01,
17 kTLVType_Salt => 0x02,
18 kTLVType_PublicKey => 0x03,
19 kTLVType_Proof => 0x04,
20 kTLVType_EncryptedData => 0x05,
21 kTLVType_State => 0x06,
22 kTLVType_Error => 0x07,
23 kTLVType_RetryDelay => 0x08,
24 kTLVType_Certificate => 0x09,
25 kTLVType_Signature => 0x0A,
26 kTLVType_Permissions => 0x0B,
27 kTLVType_FragmentData => 0x0C,
28 kTLVType_FragmentLast => 0x0D,
29 kTLVType_SessionID => 0x0E,
30 kTLVType_Flags => 0x13,
31 kTLVType_Separator => 0xFF,
32 1 };
33  
34 # Error codes
35 1 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
36 1 kTLVError_Unknown => 0x01,
37 kTLVError_Authentication => 0x02,
38 kTLVError_Backoff => 0x03,
39 kTLVError_MaxPeers => 0x04,
40 kTLVError_MaxTries => 0x05,
41 kTLVError_Unavailable => 0x06,
42 kTLVError_Busy => 0x07,
43 1 };
44  
45 # Maximum failed authentication attempts before lockout (per HAP-Pairing.md §8)
46 1 ▶use constant MAX_AUTH_ATTEMPTS => 100;
Subroutine BEGIN: called CC=1 SCAR=0.0
47  
48 1 ▶sub new ( $class, %args )
Subroutine new: called CC=4 SCAR=20.9
Pod undocumented
49 {
50 1 ▶ my $pin = normalize_setup_code( $args{pin} ) // die "PIN required";
Condition50%1/2
normalize_setup_code($args{"pin"}) // die("PIN required")
l!l
10
MC/DC0%0/1
normalize_setup_code($args{"pin"}) // die("PIN required")
normalize_setup_code($args{"pin"})
Truth table50%1/2
A
A= normalize_setup_code($args{"pin"})
Aresult
11
00
51  
52 # The store is required. The attempt counter of HAP-Pairing.md
53 # §8 needs persistence; a silent in-memory fallback would fail
54 # open after a restart.
55 1 ▶ my $store = $args{store} // die "store required";
Condition50%1/2
$args{"store"} // die("store required")
l!l
01
MC/DC0%0/1
$args{"store"} // die("store required")
$args{"store"}
Truth table50%1/2
A
A= $args{"store"}
Aresult
11
00
56  
57 my $self = bless {
58 pin => $pin,
59 store => $store,
60 logger => $args{logger} // Protocol::HAP->null_logger,
61 accessory_ltsk => $args{accessory_ltsk},
62 accessory_ltpk => $args{accessory_ltpk},
63  
64 # The pairing lock and the attempt counter are instance
65 # state. Two servers in one process must not share a
66 # lock or a counter.
67 0 ▶ pairing_in_progress => 0,
Condition0%0/3
$args{"logger"} // "Protocol::HAP"->null_logger
l!l&&r!l&&!r
000
MC/DC0%0/2
$args{"logger"} // "Protocol::HAP"->null_logger
$args{"logger"} "Protocol::HAP"->null_logger
Truth table0%0/3
A // B
A= $args{"logger"}B= "Protocol::HAP"->null_logger
ABresult
1X1
011
000
68 pairing_session_id => undef,
69  
70 # Restore the persisted attempt counter so the limit
71 # survives restarts (HAP-Pairing.md §8)
72 failed_auth_attempts => $store->get_auth_attempts,
73 }, $class;
74  
75 0 return $self;
76 }
77  
78 # $self->clear_pairing_state($session):
79 # Reset the pairing lock. The server calls this after successful
80 # pairing or on connection close.
81 0 ▶sub clear_pairing_state ( $self, $session = undef )
Subroutine clear_pairing_state: not called CC=5 SCAR=34.0
Pod undocumented
82 0 {
83 # Clear the state only if this session owns the lock or
84 # the caller gives no session
85 0 ▶ if ( !defined $session
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $session && defined $self->{"pairing_session_id"} or $self->{"pairing_session_id"} == $session) 0 0 0
Condition0%0/6
not defined $session && defined $self->{"pairing_session_id"} or $self->{"pairing_session_id"} == $session
l!l&&r!l&&!r
000
defined $session && defined $self->{'pairing_session_id'}
!ll&&!rl&&r
000
MC/DC0%0/3
not defined $session && defined $self->{"pairing_session_id"} or $self->{"pairing_session_id"} == $session
defined $session defined $self->{'pairing_session_id'} $self->{"pairing_session_id"} == $session
Truth table0%0/4
not(A && B) or C
A= defined $sessionB= defined $self->{'pairing_session_id'}C= $self->{"pairing_session_id"} == $session
ABCresult
0XX1
10X1
1111
1100
86 || !defined $self->{pairing_session_id}
87 || $self->{pairing_session_id} == $session )
88 {
89 0 $self->{pairing_in_progress} = 0;
90 0 $self->{pairing_session_id} = undef;
91 }
92  
93 0 return;
94 }
95  
96 # $self->reset_auth_attempts:
97 # Reset the failed authentication counter. The server calls this
98 # after the SRP proof verification succeeds. Administrative
99 # actions also call it.
100 0 ▶sub reset_auth_attempts ($self)
Subroutine reset_auth_attempts: not called CC=1 SCAR=6.9
Pod undocumented
101 {
102 0 $self->{failed_auth_attempts} = 0;
103 0 $self->{store}->set_auth_attempts(0);
104  
105 0 return;
106 }
107  
108 # $self->_auth_failure($message):
109 # Count and persist a failed attempt (§8), log it with the
110 # attempt count, and return the M4 error response: MaxTries at
111 # the limit, Authentication below it.
112 0 ▶sub _auth_failure ( $self, $message )
Subroutine _auth_failure: not called CC=2 SCAR=17.9
113 {
114 0 $self->{failed_auth_attempts}++;
115 0 $self->{store}->set_auth_attempts( $self->{failed_auth_attempts} );
116  
117 $self->{logger}->warning(
118 '%s (attempt %d/%d)',
119 $message, $self->{failed_auth_attempts},
120 0 MAX_AUTH_ATTEMPTS
121 );
122  
123 0 ▶ if ( $self->{failed_auth_attempts} >= MAX_AUTH_ATTEMPTS ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"failed_auth_attempts"} >= 100) 0 0 0
124 0 return $self->_error_response( kTLVError_MaxTries, 4 );
125 }
126 0 return $self->_error_response( kTLVError_Authentication, 4 );
127 }
128  
129 # $self->get_failed_attempts:
130 # Get the current failed attempt count (for testing).
131 0 ▶sub get_failed_attempts ($self)
Subroutine get_failed_attempts: not called CC=1 SCAR=6.9
Pod undocumented
132 {
133 0 return $self->{failed_auth_attempts};
134 }
135  
136 # $self->_decode_request($body, $label):
137 # The decode-and-check preamble of both pairing endpoints.
138 # Return the request TLV as a hash reference and the state, or
139 # the empty list for a malformed TLV or a missing State
140 # ([HAP-TLV8 §10]).
141 0 ▶sub _decode_request ( $self, $body, $label )
Subroutine _decode_request: not called CC=2 SCAR=17.9
142 {
143 0 my %request = Protocol::HAP::TLV::decode($body);
144  
145 0 ▶ unless ( defined $request{ kTLVType_State() } ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $request{6}) 0 0 0
146 $self->{logger}
147 0 ->warning( '%s rejected: malformed TLV request', $label );
148 0 return;
149 }
150  
151 0 return ( \%request, unpack( 'C', $request{ kTLVType_State() } ) );
152 }
153  
154 0 ▶sub handle_pair_setup ( $self, $body, $session )
Subroutine handle_pair_setup: not called CC=8 SCAR=42.8
Pod undocumented
155 {
156 0 my ( $request, $state ) = $self->_decode_request( $body, 'Pair-setup' );
157 0 ▶ return $self->_error_response( kTLVError_Unknown, 2 ) unless $request;
Branch: 1 branch
BranchTrueFalseTotal
unless $request 0 0 0
158  
159 0 ▶ my $method = unpack( 'C', $request->{ kTLVType_Method() } // "\x00" );
Condition0%0/2
$request->{0} // "\0"
l!l
00
MC/DC0%0/1
$request->{0} // "\0"
$request->{0}
Truth table0%0/2
A
A= $request->{0}
Aresult
11
00
160 $self->{logger}
161 0 ->debug( 'Pair-setup M%d received (method=%d)', $state, $method );
162  
163 # Validate the method (0x00 = PairSetup, 0x01 = PairSetupWithAuth)
164 0 ▶ if ( $method != 0 && $method != 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method != 0 and $method != 1) 0 0 0
Condition0%0/3
$method != 0 and $method != 1
!ll&&!rl&&r
000
MC/DC0%0/2
$method != 0 and $method != 1
$method != 0 $method != 1
Truth table0%0/3
A and B
A= $method != 0B= $method != 1
ABresult
0X0
100
111
165 0 return $self->_error_response( kTLVError_Unknown, 2 );
166 }
167  
168 0 ▶ if ( $state == 1 ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($state == 1) { } 0 0 0
elsif ($state == 3) { } 0 0 0
elsif ($state == 5) { } 0 0 0
169 0 return $self->_pair_setup_m1_m2( $session, $method );
170 }
171 elsif ( $state == 3 ) {
172 0 return $self->_pair_setup_m3_m4( $request, $session );
173 }
174 elsif ( $state == 5 ) {
175 0 return $self->_pair_setup_m5_m6( $request, $session );
176 }
177  
178 0 return $self->_error_response( kTLVError_Unknown, 2 );
179 }
180  
181 0 ▶sub _pair_setup_m1_m2 ( $self, $session, $method = 0 )
Subroutine _pair_setup_m1_m2: not called CC=7 SCAR=40.3
182 {
183 # Check if the failed attempts exceed the maximum
184 # (HAP-Pairing.md §8)
185 0 ▶ if ( $self->{failed_auth_attempts} >= MAX_AUTH_ATTEMPTS ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"failed_auth_attempts"} >= 100) 0 0 0
186 $self->{logger}
187 0 ->warning('Pair-setup rejected: max attempts exceeded');
188 0 return $self->_error_response( kTLVError_MaxTries, 2 );
189 }
190  
191 # Check if the accessory is already paired
192 # (HAP-Pairing.md §2.4). PairSetupWithAuth (method=1)
193 # permits pairing even when the accessory is already
194 # paired.
195 0 ▶ if ( $method == 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method == 0) 0 0 0
196 0 my $pairings = $self->{store}->load_pairings();
197 0 ▶ if ( keys %$pairings > 0 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %$pairings > 0) 0 0 0
198 $self->{logger}
199 0 ->debug('Pair-setup rejected: already paired');
200 0 return $self->_error_response( kTLVError_Unavailable,
201 2 );
202 }
203 }
204  
205 # Check for a concurrent pairing attempt (HAP-Pairing.md §2.4)
206 0 ▶ if ( $self->{pairing_in_progress}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"pairing_in_progress"} and $self->{"pairing_session_id"} != $session) 0 0 0
Condition0%0/3
$self->{"pairing_in_progress"} and $self->{"pairing_session_id"} != $session
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"pairing_in_progress"} and $self->{"pairing_session_id"} != $session
$self->{"pairing_in_progress"} $self->{"pairing_session_id"} != $session
Truth table0%0/3
A and B
A= $self->{"pairing_in_progress"}B= $self->{"pairing_session_id"} != $session
ABresult
0X0
100
111
207 && $self->{pairing_session_id} != $session )
208 {
209 $self->{logger}
210 0 ->debug('Pair-setup rejected: another pairing in progress');
211 0 return $self->_error_response( kTLVError_Busy, 2 );
212 }
213  
214 # Mark the pairing as in progress
215 0 $self->{pairing_in_progress} = 1;
216 0 $self->{pairing_session_id} = $session;
217  
218 # Initialize SRP
219 0 my $srp = Protocol::HAP::SRP->new( password => $self->{pin} );
220 0 my $salt = $srp->generate_salt();
221 0 $srp->compute_verifier;
222 0 $srp->generate_server_public();
223  
224 # Store the SRP session
225 0 $session->{pairing_state}{srp} = $srp;
226  
227 # M2: Send the salt and the public key. The key goes out padded
228 # to the length of N, which is what both sides hash.
229 0 my $response =
230 Protocol::HAP::TLV::encode( kTLVType_State, pack( 'C', 2 ),
231 kTLVType_PublicKey, $srp->server_public_bytes,
232 kTLVType_Salt, $salt, );
233  
234 0 return $response;
235 }
236  
237 0 ▶sub _pair_setup_m3_m4 ( $self, $request, $session )
Subroutine _pair_setup_m3_m4: not called CC=4 SCAR=30.0
238 {
239  
240 0 my $srp = $session->{pairing_state}{srp};
241 0 ▶ return $self->_error_response( kTLVError_Unknown, 4 ) unless $srp;
Branch: 1 branch
BranchTrueFalseTotal
unless $srp 0 0 0
242  
243 0 my $A = $request->{ kTLVType_PublicKey() };
244 0 my $M1 = $request->{ kTLVType_Proof() };
245  
246 # Compute the session key. It returns undef if A mod N == 0.
247 0 my $K = $srp->compute_session_key($A);
248 0 ▶ unless ( defined $K ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $K) 0 0 0
249 0 return $self->_auth_failure(
250 'Pair-setup M3 rejected: invalid public key A');
251 }
252  
253 0 ▶ unless ( $srp->verify_client_proof($M1) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($srp->verify_client_proof($M1)) 0 0 0
254 0 return $self->_auth_failure(
255 'Pair-setup M3 proof verification failed');
256 }
257  
258 # Successful SRP proof resets the attempt counter (§8)
259 0 $self->reset_auth_attempts;
260  
261 # Generate the server proof
262 0 my $M2 = $srp->generate_server_proof();
263 0 $self->{logger}->debug('Pair-setup M3 verified, sending M4');
264  
265 # M4: Send the proof
266 0 my $response =
267 Protocol::HAP::TLV::encode( kTLVType_State, pack( 'C', 4 ),
268 kTLVType_Proof, $M2, );
269  
270 0 return $response;
271 }
272  
273 0 ▶sub _pair_setup_m5_m6 ( $self, $request, $session )
Subroutine _pair_setup_m5_m6: not called CC=4 SCAR=30.0
274 {
275  
276 0 my $srp = $session->{pairing_state}{srp};
277 0 ▶ return $self->_error_response( kTLVError_Unknown, 6 ) unless $srp;
Branch: 1 branch
BranchTrueFalseTotal
unless $srp 0 0 0
278  
279 0 my $encrypted_data = $request->{ kTLVType_EncryptedData() };
280  
281 # Derive the encryption key from the SRP session key
282 0 my $session_key = $srp->session_key;
283 0 my $encrypt_key = Protocol::HAP::Crypto->hkdf_sha512( $session_key,
284 'Pair-Setup-Encrypt-Salt', 'Pair-Setup-Encrypt-Info', 32 );
285  
286 # Decrypt the data
287 0 my $nonce = pack('x[4]') . 'PS-Msg05';
288 0 my $auth_tag = substr( $encrypted_data, -16, 16, '' );
289 0 my $decrypted =
290 Protocol::HAP::Crypto->chacha20poly1305_decrypt( $encrypt_key,
291 $nonce, $encrypted_data, $auth_tag );
292  
293 0 ▶ return $self->_error_response( kTLVError_Authentication, 6 )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decrypted 0 0 0
294 unless defined $decrypted;
295  
296 # Parse the decrypted TLV
297 0 my %inner = Protocol::HAP::TLV::decode($decrypted);
298 0 my $ios_device_pairing_id = $inner{ kTLVType_Identifier() };
299 0 my $ios_device_ltpk = $inner{ kTLVType_PublicKey() };
300 0 my $ios_device_signature = $inner{ kTLVType_Signature() };
301  
302 # Verify the signature
303 0 my $ios_device_x = Protocol::HAP::Crypto->hkdf_sha512(
304 $session_key,
305 'Pair-Setup-Controller-Sign-Salt',
306 'Pair-Setup-Controller-Sign-Info', 32
307 );
308 0 my $ios_device_info =
309 $ios_device_x . $ios_device_pairing_id . $ios_device_ltpk;
310  
311 0 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless ("Protocol::HAP::Crypto"->ed25519_verify($ios_device_signature, $ios_device_info, $ios_device_ltpk)) 0 0 0
312 Protocol::HAP::Crypto->ed25519_verify(
313 $ios_device_signature, $ios_device_info,
314 $ios_device_ltpk
315 ) )
316 {
317 0 return $self->_error_response( kTLVError_Authentication, 6 );
318 }
319  
320 # Save the pairing
321 $self->{store}
322 0 ->save_pairing( $ios_device_pairing_id, $ios_device_ltpk, 1 );
323 0 $self->{logger}->debug( 'Pair-setup M5 verified, pairing saved for %s',
324 $ios_device_pairing_id );
325  
326 # The pairing is successful. Reset the attempt counter.
327 # Clear the pairing lock.
328 0 $self->reset_auth_attempts;
329 0 $self->{pairing_in_progress} = 0;
330 0 $self->{pairing_session_id} = undef;
331  
332 # Generate the accessory signature
333 0 my $accessory_x = Protocol::HAP::Crypto->hkdf_sha512(
334 $session_key,
335 'Pair-Setup-Accessory-Sign-Salt',
336 'Pair-Setup-Accessory-Sign-Info', 32
337 );
338 my $accessory_pairing_id =
339 0 Protocol::HAP::device_id( $self->{accessory_ltpk} );
340 my $accessory_info =
341 0 $accessory_x . $accessory_pairing_id . $self->{accessory_ltpk};
342 my $accessory_signature = Protocol::HAP::Crypto->ed25519_sign(
343 $accessory_info,
344 $self->{accessory_ltsk},
345 0 $self->{accessory_ltpk} );
346  
347 # Build the response TLV
348 my $response_tlv = Protocol::HAP::TLV::encode(
349 kTLVType_Identifier, $accessory_pairing_id,
350 kTLVType_PublicKey, $self->{accessory_ltpk},
351 0 kTLVType_Signature, $accessory_signature,
352 );
353  
354 # Encrypt the response
355 0 my $response_nonce = pack('x[4]') . 'PS-Msg06';
356 0 my ( $response_encrypted, $response_tag ) =
357 Protocol::HAP::Crypto->chacha20poly1305_encrypt( $encrypt_key,
358 $response_nonce, $response_tlv );
359  
360 # M6: Send the encrypted data
361 0 my $response = Protocol::HAP::TLV::encode(
362 kTLVType_State, pack( 'C', 6 ),
363 kTLVType_EncryptedData, $response_encrypted . $response_tag,
364 );
365  
366 0 return $response;
367 }
368  
369 0 ▶sub handle_pair_verify ( $self, $body, $session )
Subroutine handle_pair_verify: not called CC=4 SCAR=30.0
Pod undocumented
370 {
371 0 my ( $request, $state ) =
372 $self->_decode_request( $body, 'Pair-verify' );
373 0 ▶ return $self->_error_response( kTLVError_Unknown, 2 ) unless $request;
Branch: 1 branch
BranchTrueFalseTotal
unless $request 0 0 0
374  
375 0 $self->{logger}->debug( 'Pair-verify M%d received', $state );
376  
377 0 ▶ if ( $state == 1 ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($state == 1) { } 0 0 0
elsif ($state == 3) { } 0 0 0
378 0 return $self->_pair_verify_m1_m2( $request, $session );
379 }
380 elsif ( $state == 3 ) {
381 0 return $self->_pair_verify_m3_m4( $request, $session );
382 }
383  
384 0 return $self->_error_response( kTLVError_Unknown, 2 );
385 }
386  
387 0 ▶sub _pair_verify_m1_m2 ( $self, $request, $session )
Subroutine _pair_verify_m1_m2: not called CC=1 SCAR=6.9
388 {
389  
390 0 my $ios_public_key = $request->{ kTLVType_PublicKey() };
391 0 $self->{logger}->debug('Pair-verify M1: generating ephemeral keypair');
392  
393 # Generate the accessory ephemeral keypair
394 0 my ( $accessory_secret, $accessory_public ) =
395 Protocol::HAP::Crypto->x25519_keypair;
396  
397 # Compute the shared secret
398 0 my $shared_secret =
399 Protocol::HAP::Crypto->x25519_shared_secret( $accessory_secret,
400 $ios_public_key );
401  
402 # Store the state for the next step
403 0 $session->{pairing_state}{accessory_secret} = $accessory_secret;
404 0 $session->{pairing_state}{accessory_public} = $accessory_public;
405 0 $session->{pairing_state}{ios_public_key} = $ios_public_key;
406 0 $session->{pairing_state}{shared_secret} = $shared_secret;
407  
408 # Generate the accessory info and signature
409 my $accessory_pairing_id =
410 0 Protocol::HAP::device_id( $self->{accessory_ltpk} );
411 0 my $accessory_info =
412 $accessory_public . $accessory_pairing_id . $ios_public_key;
413 my $accessory_signature = Protocol::HAP::Crypto->ed25519_sign(
414 $accessory_info,
415 $self->{accessory_ltsk},
416 0 $self->{accessory_ltpk} );
417  
418 # Build the sub-TLV
419 0 my $sub_tlv = Protocol::HAP::TLV::encode(
420 kTLVType_Identifier, $accessory_pairing_id,
421 kTLVType_Signature, $accessory_signature,
422 );
423  
424 # Derive the session key and encrypt
425 0 my $session_key = Protocol::HAP::Crypto->hkdf_sha512( $shared_secret,
426 'Pair-Verify-Encrypt-Salt', 'Pair-Verify-Encrypt-Info', 32 );
427  
428 0 my $nonce = pack('x[4]') . 'PV-Msg02';
429 0 my ( $encrypted, $tag ) =
430 Protocol::HAP::Crypto->chacha20poly1305_encrypt( $session_key,
431 $nonce, $sub_tlv );
432  
433 # M2: Send the public key and the encrypted data
434 0 my $response = Protocol::HAP::TLV::encode(
435 kTLVType_State, pack( 'C', 2 ),
436 kTLVType_PublicKey, $accessory_public,
437 kTLVType_EncryptedData, $encrypted . $tag,
438 );
439  
440 0 return $response;
441 }
442  
443 0 ▶sub _pair_verify_m3_m4 ( $self, $request, $session )
Subroutine _pair_verify_m3_m4: not called CC=5 SCAR=34.0
444 {
445  
446 0 my $encrypted_data = $request->{ kTLVType_EncryptedData() };
447  
448 0 my $shared_secret = $session->{pairing_state}{shared_secret};
449 0 my $accessory_public = $session->{pairing_state}{accessory_public};
450 0 my $ios_public_key = $session->{pairing_state}{ios_public_key};
451  
452 # M3 without a preceding M1 exchange is a protocol error
453 0 ▶ return $self->_error_response( kTLVError_Unknown, 4 )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $shared_secret 0 0 0
454 unless defined $shared_secret;
455  
456 # Derive the session key
457 0 my $session_key = Protocol::HAP::Crypto->hkdf_sha512( $shared_secret,
458 'Pair-Verify-Encrypt-Salt', 'Pair-Verify-Encrypt-Info', 32 );
459  
460 # Decrypt
461 0 my $nonce = pack('x[4]') . 'PV-Msg03';
462 0 my $auth_tag = substr( $encrypted_data, -16, 16, '' );
463 0 my $decrypted =
464 Protocol::HAP::Crypto->chacha20poly1305_decrypt( $session_key,
465 $nonce, $encrypted_data, $auth_tag );
466  
467 0 ▶ return $self->_error_response( kTLVError_Authentication, 4 )
Branch: 1 branch
BranchTrueFalseTotal
unless defined $decrypted 0 0 0
468 unless defined $decrypted;
469  
470 # Parse the inner TLV
471 0 my %inner = Protocol::HAP::TLV::decode($decrypted);
472 0 my $ios_pairing_id = $inner{ kTLVType_Identifier() };
473 0 my $ios_signature = $inner{ kTLVType_Signature() };
474  
475 # Load the pairing
476 0 my $pairings = $self->{store}->load_pairings();
477 0 my $pairing = $pairings->{$ios_pairing_id};
478  
479 0 ▶ return $self->_error_response( kTLVError_Authentication, 4 )
Branch: 1 branch
BranchTrueFalseTotal
unless $pairing 0 0 0
480 unless $pairing;
481  
482 # Verify the signature
483 0 my $ios_info = $ios_public_key . $ios_pairing_id . $accessory_public;
484 0 ▶ unless (
Branch: 1 branch
BranchTrueFalseTotal
unless ("Protocol::HAP::Crypto"->ed25519_verify($ios_signature, $ios_info, $pairing->{"ltpk"})) 0 0 0
485 Protocol::HAP::Crypto->ed25519_verify(
486 $ios_signature, $ios_info, $pairing->{ltpk} ) )
487 {
488 0 return $self->_error_response( kTLVError_Authentication, 4 );
489 }
490  
491 # Derive the session encryption keys. The names are from
492 # the controller's point of view:
493 # - Control-Read-Encryption-Key: the controller reads,
494 # the accessory encrypts
495 # - Control-Write-Encryption-Key: the controller writes,
496 # the accessory decrypts
497 0 my $encrypt_key =
498 Protocol::HAP::Crypto->hkdf_sha512( $shared_secret, 'Control-Salt',
499 'Control-Read-Encryption-Key', 32 );
500 0 my $decrypt_key =
501 Protocol::HAP::Crypto->hkdf_sha512( $shared_secret, 'Control-Salt',
502 'Control-Write-Encryption-Key', 32 );
503  
504 # Set up the encrypted session
505 0 $session->set_encryption( $encrypt_key, $decrypt_key );
506 0 $session->set_verified($ios_pairing_id);
507 $self->{logger}
508 0 ->debug('Pair-verify M3 verified successfully, session encrypted');
509  
510 # M4: Success
511 0 my $response =
512 Protocol::HAP::TLV::encode( kTLVType_State, pack( 'C', 4 ), );
513  
514 0 return $response;
515 }
516  
517 0 ▶sub _error_response ( $self, $error_code, $state )
Subroutine _error_response: not called CC=1 SCAR=6.9
518 {
519  
520 0 return Protocol::HAP::TLV::encode(
521 kTLVType_State, pack( 'C', $state ),
522 kTLVType_Error, pack( 'C', $error_code ),
523 );
524 }
525  
526 1 1;
« blib/lib/Protocol/HAP/Server.pm ↑ Summary blib/lib/Protocol/HAP/Session.pm »