@@ -105,7 +105,12 @@ protected DTLSTransport clientHandshake(ClientHandshakeState state)
105105
106106 handshake .sendMessage (HandshakeType .client_hello , clientHelloBody );
107107
108- DTLSReliableHandshake .Message serverMessage = handshake .receiveMessage ();
108+ /*
109+ * NOTE: Received without being digested. A HelloRetryRequest must not go into the transcript until
110+ * the first ClientHello in it has been replaced by RFC 8446 4.4.1's synthetic "message_hash"
111+ * message, and whether this is one is only known once its body has been read.
112+ */
113+ DTLSReliableHandshake .Message serverMessage = handshake .receiveMessageDelayedDigest ();
109114
110115 // TODO Consider stricter HelloVerifyRequest protocol
111116// if (serverMessage.getType() == HandshakeType.hello_verify_request)
@@ -117,11 +122,49 @@ protected DTLSTransport clientHandshake(ClientHandshakeState state)
117122 handshake .resetAfterHelloVerifyRequestClient ();
118123 handshake .sendMessage (HandshakeType .client_hello , patched );
119124
120- serverMessage = handshake .receiveMessage ();
125+ serverMessage = handshake .receiveMessageDelayedDigest ();
126+ }
127+
128+ if (serverMessage .getType () == HandshakeType .server_hello && isHelloRetryRequest (serverMessage .getBody ()))
129+ {
130+ process13HelloRetryRequest (state , serverMessage .getBody ());
131+
132+ /*
133+ * RFC 8446 4.4.1. The transcript for a handshake with a HelloRetryRequest begins with a
134+ * synthetic "message_hash" message carrying the hash of the first ClientHello alone, which
135+ * replaces it. So the first ClientHello is hashed and substituted here - reading the transcript
136+ * is what flushes it, in the DTLS 1.3 header form now that the negotiated version is known - and
137+ * only then is the HelloRetryRequest hashed after it.
138+ */
139+ TlsHandshakeHash handshakeHash = handshake .getHandshakeHash ();
140+ handshakeHash .notifyPRFDetermined ();
141+
142+ TlsUtils .adjustTranscriptForRetry (handshakeHash );
143+
144+ handshake .updateHandshakeMessagesDigest (serverMessage );
145+
146+ handshake .sendMessage (HandshakeType .client_hello , generate13ClientHelloRetry (state ));
147+
148+ state .afterHelloRetryRequest = true ;
149+
150+ serverMessage = handshake .receiveMessageDelayedDigest ();
151+
152+ /*
153+ * RFC 8446 4.1.4. If a client receives a second HelloRetryRequest in the same connection (i.e.,
154+ * where the ClientHello was itself in response to a HelloRetryRequest), it MUST abort the
155+ * handshake with an "unexpected_message" alert.
156+ */
157+ if (serverMessage .getType () == HandshakeType .server_hello && isHelloRetryRequest (serverMessage .getBody ()))
158+ {
159+ throw new TlsFatalAlert (AlertDescription .unexpected_message ,
160+ "Second HelloRetryRequest received" );
161+ }
121162 }
122163
123164 if (serverMessage .getType () == HandshakeType .server_hello )
124165 {
166+ handshake .updateHandshakeMessagesDigest (serverMessage );
167+
125168 ProtocolVersion recordLayerVersion = recordLayer .getReadVersion ();
126169
127170 /*
@@ -158,7 +201,7 @@ protected DTLSTransport clientHandshake(ClientHandshakeState state)
158201 handshake .getHandshakeHash ().notifyPRFDetermined ();
159202 handshake .getHandshakeHash ().sealHashAlgorithms ();
160203
161- process13ServerHelloCoda (state , handshake .getHandshakeHash (), false );
204+ process13ServerHelloCoda (state , handshake .getHandshakeHash (), state . afterHelloRetryRequest );
162205
163206 return clientHandshake13 (state , handshake );
164207 }
@@ -826,6 +869,223 @@ protected void invalidateSession(ClientHandshakeState state)
826869 cancelSession (state );
827870 }
828871
872+ /**
873+ * Whether a ServerHello body is a HelloRetryRequest (RFC 8446 4.1.3: a ServerHello whose 'random' is the
874+ * special value). Used only to route the message; all validation is left to
875+ * {@link #process13HelloRetryRequest} or {@link #processServerHello}.
876+ */
877+ protected static boolean isHelloRetryRequest (byte [] body )
878+ throws IOException
879+ {
880+ return ServerHello .parse (new ByteArrayInputStream (body )).isHelloRetryRequest ();
881+ }
882+
883+ /**
884+ * Mirrors TlsClientProtocol.process13HelloRetryRequest. The "cookie" extension carried here is the
885+ * RFC 8446 4.2.2 retry token: opaque to the client, which simply echoes it in its second ClientHello.
886+ */
887+ protected void process13HelloRetryRequest (ClientHandshakeState state , byte [] body )
888+ throws IOException
889+ {
890+ TlsClient client = state .client ;
891+ TlsClientContextImpl clientContext = state .clientContext ;
892+ SecurityParameters securityParameters = clientContext .getSecurityParametersHandshake ();
893+
894+ /*
895+ * RFC 9147 5.3. The second ClientHello is still a plaintext record, carrying 'legacy_record_version'
896+ * 0xFEFD.
897+ */
898+ state .recordLayer .setWriteVersion (ProtocolVersion .DTLSv12 );
899+
900+ ServerHello helloRetryRequest = ServerHello .parse (new ByteArrayInputStream (body ));
901+
902+ /*
903+ * RFC 8446 4.1.4. Upon receipt of a HelloRetryRequest, the client MUST check the legacy_version,
904+ * legacy_session_id_echo, cipher_suite, and legacy_compression_method as specified in Section 4.1.3
905+ * and then process the extensions, starting with determining the version using "supported_versions".
906+ */
907+ ProtocolVersion legacy_version = helloRetryRequest .getVersion ();
908+ byte [] legacy_session_id_echo = helloRetryRequest .getSessionID ();
909+ int cipherSuite = helloRetryRequest .getCipherSuite ();
910+ // NOTE: legacy_compression_method checked during ServerHello parsing
911+
912+ if (!ProtocolVersion .DTLSv12 .equals (legacy_version ) ||
913+ !Arrays .areEqual (state .clientHello .getSessionID (), legacy_session_id_echo ) ||
914+ !TlsUtils .isValidCipherSuiteSelection (state .clientHello .getCipherSuites (), cipherSuite ))
915+ {
916+ throw new TlsFatalAlert (AlertDescription .illegal_parameter );
917+ }
918+
919+ Hashtable extensions = helloRetryRequest .getExtensions ();
920+ if (null == extensions )
921+ {
922+ throw new TlsFatalAlert (AlertDescription .illegal_parameter , "no extensions found" );
923+ }
924+ TlsUtils .checkExtensionData13 (extensions , HandshakeType .hello_retry_request ,
925+ AlertDescription .illegal_parameter );
926+
927+ {
928+ /*
929+ * RFC 8446 4.2. Implementations MUST NOT send extension responses if the remote endpoint did not
930+ * send the corresponding extension requests, with the exception of the "cookie" extension in the
931+ * HelloRetryRequest. Upon receiving such an extension, an endpoint MUST abort the handshake with
932+ * an "unsupported_extension" alert.
933+ */
934+ Enumeration e = extensions .keys ();
935+ while (e .hasMoreElements ())
936+ {
937+ Integer extType = (Integer )e .nextElement ();
938+ int extensionType = extType .intValue ();
939+
940+ if (ExtensionType .cookie == extensionType )
941+ {
942+ continue ;
943+ }
944+
945+ if (null == TlsUtils .getExtensionData (state .clientExtensions , extType ))
946+ {
947+ throw new TlsFatalAlert (AlertDescription .unsupported_extension ,
948+ "Unrequested extension in HelloRetryRequest: " + ExtensionType .getText (extensionType ));
949+ }
950+ }
951+ }
952+
953+ ProtocolVersion server_version = TlsExtensionsUtils .getSupportedVersionsExtensionServer (extensions );
954+ if (null == server_version )
955+ {
956+ throw new TlsFatalAlert (AlertDescription .missing_extension ,
957+ "missing extension response: " + ExtensionType .getText (ExtensionType .supported_versions ));
958+ }
959+
960+ if (!ProtocolVersion .DTLSv13 .isEqualOrEarlierVersionOf (server_version ) ||
961+ server_version .isLaterVersionOf (ProtocolVersion .DTLSv13 ))
962+ {
963+ throw new TlsFatalAlert (AlertDescription .illegal_parameter ,
964+ "invalid version selected: " + server_version );
965+ }
966+
967+ if (!TlsUtils .isValidVersionForCipherSuite (cipherSuite , server_version ))
968+ {
969+ throw new TlsFatalAlert (AlertDescription .illegal_parameter , "invalid cipher suite for selected version" );
970+ }
971+
972+ if (null != state .clientBinders )
973+ {
974+ if (!Arrays .contains (state .clientBinders .pskKeyExchangeModes , PskKeyExchangeMode .psk_dhe_ke ))
975+ {
976+ state .clientBinders = null ;
977+
978+ client .notifySelectedPSK (null );
979+ }
980+ }
981+
982+ int selectedGroup = TlsExtensionsUtils .getKeyShareHelloRetryRequest (extensions );
983+
984+ /*
985+ * TODO[dtls13:psk_ke] RFC 8446 4.2.8. Servers [..] MUST NOT send a KeyShareEntry when using the
986+ * "psk_ke" PskKeyExchangeMode - and RFC 8446 4.1.4 permits a HelloRetryRequest that carries only a
987+ * cookie, which this does not yet accept.
988+ */
989+ if (selectedGroup < 0 )
990+ {
991+ throw new TlsFatalAlert (AlertDescription .missing_extension ,
992+ "missing extension response: " + ExtensionType .getText (ExtensionType .key_share ));
993+ }
994+
995+ /*
996+ * RFC 8446 4.2.8. Upon receipt of this [Key Share] extension in a HelloRetryRequest, the client MUST
997+ * verify that (1) the selected_group field corresponds to a group which was provided in the
998+ * "supported_groups" extension in the original ClientHello and (2) the selected_group field does not
999+ * correspond to a group which was provided in the "key_share" extension in the original ClientHello.
1000+ * If either of these checks fails, then the client MUST abort the handshake with an
1001+ * "illegal_parameter" alert.
1002+ */
1003+ if (!TlsUtils .isValidKeyShareSelection (server_version , securityParameters .getClientSupportedGroups (),
1004+ state .clientAgreements , selectedGroup ))
1005+ {
1006+ throw new TlsFatalAlert (AlertDescription .illegal_parameter , "invalid key_share selected" );
1007+ }
1008+
1009+ byte [] cookie = TlsExtensionsUtils .getCookieExtension (extensions );
1010+
1011+ // NOTE: Also checks that this is a version the client offered, and notifies the TlsClient
1012+ reportServerVersion (state , server_version );
1013+
1014+ securityParameters .resumedSession = false ;
1015+ securityParameters .sessionID = TlsUtils .EMPTY_BYTES ;
1016+ client .notifySessionID (TlsUtils .EMPTY_BYTES );
1017+
1018+ TlsUtils .negotiatedCipherSuite (securityParameters , cipherSuite );
1019+ client .notifySelectedCipherSuite (cipherSuite );
1020+
1021+ securityParameters .negotiatedGroup = selectedGroup ;
1022+
1023+ state .clientAgreements = null ;
1024+ state .retryCookie = cookie ;
1025+ state .retryGroup = selectedGroup ;
1026+ }
1027+
1028+ /**
1029+ * Mirrors TlsClientProtocol.send13ClientHelloRetry, except that the message goes out through
1030+ * DTLSReliableHandshake and RFC 9147 5 drops the TLS 1.3 compatibility-mode change_cipher_spec that
1031+ * precedes it there.
1032+ * <p>
1033+ * RFC 8446 4.1.2: the second ClientHello repeats the first unchanged except for the "key_share",
1034+ * "early_data", "cookie", "pre_shared_key" and "padding" extensions, which is why the ClientHello object
1035+ * itself is kept and re-encoded. Its 'legacy_cookie' field stays empty: RFC 9147 5.3 keeps that field
1036+ * only for backwards compatibility with the DTLS 1.2 HelloVerifyRequest exchange.
1037+ * </p>
1038+ */
1039+ protected byte [] generate13ClientHelloRetry (ClientHandshakeState state )
1040+ throws IOException
1041+ {
1042+ ClientHello clientHello = state .clientHello ;
1043+ Hashtable clientHelloExtensions = clientHello .getExtensions ();
1044+
1045+ clientHelloExtensions .remove (TlsExtensionsUtils .EXT_cookie );
1046+ clientHelloExtensions .remove (TlsExtensionsUtils .EXT_early_data );
1047+ clientHelloExtensions .remove (TlsExtensionsUtils .EXT_key_share );
1048+ clientHelloExtensions .remove (TlsExtensionsUtils .EXT_pre_shared_key );
1049+
1050+ /*
1051+ * RFC 8446 4.2.2. When sending the new ClientHello, the client MUST copy the contents of the
1052+ * extension received in the HelloRetryRequest into a "cookie" extension in the new ClientHello.
1053+ */
1054+ if (null != state .retryCookie )
1055+ {
1056+ TlsExtensionsUtils .addCookieExtension (clientHelloExtensions , state .retryCookie );
1057+ state .retryCookie = null ;
1058+ }
1059+
1060+ /*
1061+ * TODO[dtls13-psk] Update the "pre_shared_key" extension if present, by recomputing the
1062+ * "obfuscated_ticket_age" and binder values (TlsUtils.addPreSharedKeyToClientHelloRetry). No PSK is
1063+ * ever offered yet, so there is nothing to recompute.
1064+ */
1065+
1066+ /*
1067+ * RFC 8446 4.2.8. [..] when sending the new ClientHello, the client MUST replace the original
1068+ * "key_share" extension with one containing only a new KeyShareEntry for the group indicated in the
1069+ * selected_group field of the triggering HelloRetryRequest.
1070+ */
1071+ if (state .retryGroup < 0 )
1072+ {
1073+ throw new TlsFatalAlert (AlertDescription .internal_error );
1074+ }
1075+
1076+ state .clientAgreements = TlsUtils .addKeyShareToClientHelloRetry (state .clientContext ,
1077+ clientHelloExtensions , state .retryGroup );
1078+
1079+ /*
1080+ * TODO[dtls13] Optionally adding, removing, or changing the length of the "padding" extension
1081+ * [RFC7685].
1082+ */
1083+
1084+ ByteArrayOutputStream buf = new ByteArrayOutputStream ();
1085+ clientHello .encode (state .clientContext , buf );
1086+ return buf .toByteArray ();
1087+ }
1088+
8291089 /**
8301090 * Mirrors TlsClientProtocol.process13ServerHello: check the ServerHello against the ClientHello that was
8311091 * sent, then run the RFC 8446 7.1 key schedule as far as the handshake secret.
@@ -837,11 +1097,14 @@ protected void process13ServerHello(ClientHandshakeState state, ServerHello serv
8371097 TlsClientContextImpl clientContext = state .clientContext ;
8381098 SecurityParameters securityParameters = clientContext .getSecurityParametersHandshake ();
8391099
1100+ /*
1101+ * RFC 8446 4.1.4. A HelloRetryRequest is handled in clientHandshake, ahead of this; reaching here
1102+ * with one means a second one, which must be refused.
1103+ */
8401104 if (serverHello .isHelloRetryRequest ())
8411105 {
842- // TODO[dtls13] HelloRetryRequest (with its cookie extension) is not implemented yet
8431106 throw new TlsFatalAlert (AlertDescription .unexpected_message ,
844- "DTLS 1.3 HelloRetryRequest is not implemented " );
1107+ "HelloRetryRequest received where a ServerHello was expected " );
8451108 }
8461109
8471110 ProtocolVersion legacy_version = serverHello .getVersion ();
@@ -1305,17 +1568,16 @@ protected void processServerHello(ClientHandshakeState state, byte[] body)
13051568
13061569 if (ProtocolVersion .DTLSv13 .isEqualOrEarlierVersionOf (server_version ))
13071570 {
1308- process13ServerHello (state , serverHello , false );
1571+ process13ServerHello (state , serverHello , state . afterHelloRetryRequest );
13091572 return ;
13101573 }
13111574
13121575 int [] offeredCipherSuites = state .offeredCipherSuites ;
13131576
13141577 state .clientHello = null ;
13151578
1316- // TODO[dtls13]
1317- // state.retryCookie = null;
1318- // state.retryGroup = -1;
1579+ state .retryCookie = null ;
1580+ state .retryGroup = -1 ;
13191581
13201582 securityParameters .serverRandom = serverHello .getRandom ();
13211583
@@ -1702,6 +1964,9 @@ protected static class ClientHandshakeState
17021964 boolean expectSessionTicket = false ;
17031965 Hashtable clientAgreements = null ;
17041966 OfferedPsks .BindersConfig clientBinders = null ;
1967+ boolean afterHelloRetryRequest = false ;
1968+ byte [] retryCookie = null ;
1969+ int retryGroup = -1 ;
17051970 TlsKeyExchange keyExchange = null ;
17061971 TlsAuthentication authentication = null ;
17071972 CertificateStatus certificateStatus = null ;
0 commit comments