CVE-2023-48795 (published 2023-12-18T16:15Z)

The SSH transport protocol with certain OpenSSH extensions, found in OpenSSH before 9.6 and other products, allows remote attackers to bypass integrity checks such that some packets are omitted (from the extension negotiation message), and a client and server may consequently end up with a connection for which some security features have been downgraded or disabled, aka a Terrapin attack. This occurs because the SSH Binary Packet Protocol (BPP), implemented by these extensions, mishandles the handshake phase and mishandles use of sequence numbers. For example, there is an effective attack against SSH's use of ChaCha20-Poly1305 (and CBC with Encrypt-then-MAC). The bypass occurs in chacha20-poly1305@openssh.com and (if CBC is used) the -etm@openssh.com MAC algorithms. This also affects Maverick Synergy Java SSH API before 3.1.0-SNAPSHOT, Dropbear through 2022.83, Ssh before 5.1.1 in Erlang/OTP, PuTTY before 0.80, AsyncSSH before 2.14.2, golang.org/x/crypto before 0.17.0, libssh before 0.10.6, libssh2 through 1.11.0, Thorn Tech SFTP Gateway before 3.4.6, Tera Term before 5.1, Paramiko before 3.4.0, jsch before 0.2.15, SFTPGo before 2.5.6, Netgate pfSense Plus through 23.09.1, Netgate pfSense CE through 2.7.2, HPN-SSH through 18.2.0, ProFTPD before 1.3.8b (and before 1.3.9rc2), ORYX CycloneSSH before 2.3.4, NetSarang XShell 7 before Build 0144, CrushFTP before 10.6.0, ConnectBot SSH library before 2.2.22, Apache MINA sshd through 2.11.0, sshj through 0.37.0, TinySSH through 20230101, trilead-ssh2 6401, LANCOM LCOS and LANconfig, FileZilla before 3.66.4, Nova before 11.8, PKIX-SSH before 14.4, SecureCRT before 9.4.3, Transmit5 before 5.10.4, Win32-OpenSSH before 9.5.0.0p1-Beta, WinSCP before 6.2.2, Bitvise SSH Server before 9.32, Bitvise SSH Client before 9.33, KiTTY through 0.76.1.13, the net-ssh gem 7.2.0 for Ruby, the mscdex ssh2 module before 1.15.0 for Node.js, the thrussh library before 0.35.1 for Rust, and the Russh crate before 0.40.2 for Rust.

CVSS v3 base score: 5.9, MEDIUM (CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N)

Weakness information:
cwe_id: CWE-354
cwe_name: Improper Validation of Integrity Check Value
description: The product does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
extended_description: Improper validation of checksums before use results in an unnecessary risk that can easily be mitigated. The protocol specification describes the algorithm used for calculating the checksum. It is then a simple matter of implementing the calculation and verifying that the calculated checksum and the received checksum match. Improper verification of the calculated checksum and the received checksum can lead to far greater consequences.
         

Fix information:
repo_url: https://github.com/TeraTermProject/teraterm
commit_details: repo_url: https://github.com/TeraTermProject/teraterm
author: IWAMOTO Kouichi
author_date: 2023-12-05 05:34:15+09:00
msg: Strict KEX 対応 (CVE-2023-48795)

とりあえず Strict KEX のネゴシエーションとシーケンス番号のリセットに対応。
repository: repo_url: https://github.com/TeraTermProject/teraterm
repo_name: TeraTermProject/teraterm
repo_language: C
owner: TeraTermProject
file_changes: filename: kex.c
change_type: ModificationType.MODIFY
diff: @@ -146,8 +146,8 @@ void SSH2_update_kex_myproposal(PTInstVar pvar)
 			// L[č쐬̏ꍇɂ́Aڑ pvar->settings gݗĂꂽ myproposal B
 			//   pvar->settings  ڑ myproposal 쐬Ƃ̒lςĂȂۏ؂ȂB
 			//   ēxgݗĂ̂ł͂Ȃ myproposal 邱ƂɂB
-			int pos = strlen(myproposal[PROPOSAL_KEX_ALGS]) - strlen(",ext-info-c");
-			if (strcmp(myproposal[PROPOSAL_KEX_ALGS] + pos, ",ext-info-c") == 0) {
+			int pos = strlen(myproposal[PROPOSAL_KEX_ALGS]) - strlen(",ext-info-c,kex-strict-c-v00@openssh.com");
+			if (strcmp(myproposal[PROPOSAL_KEX_ALGS] + pos, ",ext-info-c,kex-strict-c-v00@openssh.com") == 0) {
 				myproposal[PROPOSAL_KEX_ALGS][pos] = '\0';
 			}
 		}
@@ -163,8 +163,8 @@ void SSH2_update_kex_myproposal(PTInstVar pvar)
 		strncat_s(buf, sizeof(buf), ",", _TRUNCATE);
 	}
 
-	// RFC 8308 Extension Negotiation
-	strncat_s(buf, sizeof(buf), "ext-info-c", _TRUNCATE);
+	// Enables RFC 8308 Extension Negotiation & Strict KEX mode (for CVE-2023-48795)
+	strncat_s(buf, sizeof(buf), "ext-info-c,kex-strict-c-v00@openssh.com", _TRUNCATE);
 
 	myproposal[PROPOSAL_KEX_ALGS] = buf; 
 }

programming_language: C++
filename: ssh.c
change_type: ModificationType.MODIFY
diff: @@ -2997,6 +2997,7 @@ void SSH_init(PTInstVar pvar)
 	pvar->use_subsystem = FALSE;
 	pvar->nosession = FALSE;
 	pvar->server_sig_algs = NULL;
+	pvar->server_strict_kex = FALSE;
 
 }
 
@@ -4813,7 +4814,7 @@ static BOOL handle_SSH2_kexinit(PTInstVar pvar)
 	if (pvar->kex_status == KEX_FLAG_KEXDONE) {
 		pvar->kex_status = KEX_FLAG_REKEYING;
 
-		// L[č쐬 myproposal  ",ext-info-c" 폜
+		// L[č쐬 myproposal  ",ext-info-c,kex-strict-c-v00@openssh.com" 폜
 		// XV̂ KEX ݂̂ł悢
 		SSH2_update_kex_myproposal(pvar);
 
@@ -4878,6 +4879,13 @@ static BOOL handle_SSH2_kexinit(PTInstVar pvar)
 		goto error;
 	}
 
+	// T[o[Strict KEXɑΉĂ邩̊mF
+	choose_SSH2_proposal(buf, "kex-strict-s-v00@openssh.com", tmp, sizeof(tmp));
+	if (tmp[0] != '\0') {
+		pvar->server_strict_kex = TRUE;
+		logprintf(LOG_LEVEL_INFO, "Server supports strict kex. Strict kex will be enabled.");
+	}
+
 	// zXgASY
 	switch (get_namelist_from_payload(pvar, buf, sizeof(buf), &size)) {
 	case GetPayloadError:
@@ -5644,6 +5652,10 @@ static void ssh2_send_newkeys(PTInstVar pvar)
 
 	pvar->kex_status |= KEX_FLAG_NEWKEYS_SENT;
 
+	if (pvar->server_strict_kex) {
+		pvar->ssh_state.sender_sequence_number = 0;
+	}
+
 	// SSH2_MSG_NEWKEYS Ɏ󂯎ĂKEX͊B̏ɈڂB
 	if (pvar->kex_status & KEX_FLAG_NEWKEYS_RECEIVED) {
 		if ((pvar->kex_status & KEX_FLAG_REKEYING)) {
@@ -6238,6 +6250,10 @@ static BOOL handle_SSH2_newkeys(PTInstVar pvar)
 	pvar->ssh2_keys[MODE_IN].comp.enabled = 1;
 	enable_recv_compression(pvar);
 
+	if (pvar->server_strict_kex) {
+		pvar->ssh_state.receiver_sequence_number = 0;
+	}
+
 	SSH2_dispatch_add_message(SSH2_MSG_EXT_INFO);
 
 	// SSH2_MSG_NEWKEYS ɑĂKEX͊B̏ɈڂB

programming_language: C
filename: ttxssh.h
change_type: ModificationType.MODIFY
diff: @@ -363,6 +363,7 @@ typedef struct _TInstVar {
 	} recv;
 
 	char *server_sig_algs;
+	BOOL server_strict_kex;
 
 	char UIMsg[MAX_UIMSG];
 } TInstVar;

programming_language: C++
repo_url: https://github.com/golang/crypto
commit_details: repo_url: https://github.com/golang/crypto
author: Roland Shoemaker
author_date: 2023-11-20 12:06:18-08:00
msg: ssh: implement strict KEX protocol changes

Implement the "strict KEX" protocol changes, as described in section
1.9 of the OpenSSH PROTOCOL file (as of OpenSSH version 9.6/9.6p1).

Namely this makes the following changes:
  * Both the server and the client add an additional algorithm to the
    initial KEXINIT message, indicating support for the strict KEX mode.
  * When one side of the connection sees the strict KEX extension
    algorithm, the strict KEX mode is enabled for messages originating
    from the other side of the connection. If the sequence number for
    the side which requested the extension is not 1 (indicating that it
    has already received non-KEXINIT packets), the connection is
    terminated.
  * When strict kex mode is enabled, unexpected messages during the
    handshake are considered fatal. Additionally when a key change
    occurs (on the receipt of the NEWKEYS message) the message sequence
    numbers are reset.

Thanks to Fabian Bäumer, Marcus Brinkmann, and Jörg Schwenk from Ruhr
University Bochum for reporting this issue.

Fixes CVE-2023-48795
Fixes golang/go#64784

Change-Id: I96b53afd2bd2fb94d2b6f2a46a5dacf325357604
Reviewed-on: https://go-review.googlesource.com/c/crypto/+/550715
Reviewed-by: Nicola Murino <nicola.murino@gmail.com>
Reviewed-by: Tatiana Bradley <tatianabradley@google.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Run-TryBot: Roland Shoemaker <roland@golang.org>
Reviewed-by: Damien Neil <dneil@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
repository: repo_url: https://github.com/golang/crypto
repo_name: golang/crypto
description: [mirror] Go supplementary cryptography libraries
repo_language: Go
owner: golang
file_changes: filename: handshake.go
change_type: ModificationType.MODIFY
diff: @@ -35,6 +35,16 @@ type keyingTransport interface {
 	// direction will be effected if a msgNewKeys message is sent
 	// or received.
 	prepareKeyChange(*algorithms, *kexResult) error
+
+	// setStrictMode sets the strict KEX mode, notably triggering
+	// sequence number resets on sending or receiving msgNewKeys.
+	// If the sequence number is already > 1 when setStrictMode
+	// is called, an error is returned.
+	setStrictMode() error
+
+	// setInitialKEXDone indicates to the transport that the initial key exchange
+	// was completed
+	setInitialKEXDone()
 }
 
 // handshakeTransport implements rekeying on top of a keyingTransport
@@ -100,6 +110,10 @@ type handshakeTransport struct {
 
 	// The session ID or nil if first kex did not complete yet.
 	sessionID []byte
+
+	// strictMode indicates if the other side of the handshake indicated
+	// that we should be following the strict KEX protocol restrictions.
+	strictMode bool
 }
 
 type pendingKex struct {
@@ -209,7 +223,10 @@ func (t *handshakeTransport) readLoop() {
 			close(t.incoming)
 			break
 		}
-		if p[0] == msgIgnore || p[0] == msgDebug {
+		// If this is the first kex, and strict KEX mode is enabled,
+		// we don't ignore any messages, as they may be used to manipulate
+		// the packet sequence numbers.
+		if !(t.sessionID == nil && t.strictMode) && (p[0] == msgIgnore || p[0] == msgDebug) {
 			continue
 		}
 		t.incoming <- p
@@ -441,6 +458,11 @@ func (t *handshakeTransport) readOnePacket(first bool) ([]byte, error) {
 	return successPacket, nil
 }
 
+const (
+	kexStrictClient = "kex-strict-c-v00@openssh.com"
+	kexStrictServer = "kex-strict-s-v00@openssh.com"
+)
+
 // sendKexInit sends a key change message.
 func (t *handshakeTransport) sendKexInit() error {
 	t.mu.Lock()
@@ -454,7 +476,6 @@ func (t *handshakeTransport) sendKexInit() error {
 	}
 
 	msg := &kexInitMsg{
-		KexAlgos:                t.config.KeyExchanges,
 		CiphersClientServer:     t.config.Ciphers,
 		CiphersServerClient:     t.config.Ciphers,
 		MACsClientServer:        t.config.MACs,
@@ -464,6 +485,13 @@ func (t *handshakeTransport) sendKexInit() error {
 	}
 	io.ReadFull(rand.Reader, msg.Cookie[:])
 
+	// We mutate the KexAlgos slice, in order to add the kex-strict extension algorithm,
+	// and possibly to add the ext-info extension algorithm. Since the slice may be the
+	// user owned KeyExchanges, we create our own slice in order to avoid using user
+	// owned memory by mistake.
+	msg.KexAlgos = make([]string, 0, len(t.config.KeyExchanges)+2) // room for kex-strict and ext-info
+	msg.KexAlgos = append(msg.KexAlgos, t.config.KeyExchanges...)
+
 	isServer := len(t.hostKeys) > 0
 	if isServer {
 		for _, k := range t.hostKeys {
@@ -488,17 +516,24 @@ func (t *handshakeTransport) sendKexInit() error {
 				msg.ServerHostKeyAlgos = append(msg.ServerHostKeyAlgos, keyFormat)
 			}
 		}
+
+		if t.sessionID == nil {
+			msg.KexAlgos = append(msg.KexAlgos, kexStrictServer)
+		}
 	} else {
 		msg.ServerHostKeyAlgos = t.hostKeyAlgorithms
 
 		// As a client we opt in to receiving SSH_MSG_EXT_INFO so we know what
 		// algorithms the server supports for public key authentication. See RFC
 		// 8308, Section 2.1.
+		//
+		// We also send the strict KEX mode extension algorithm, in order to opt
+		// into the strict KEX mode.
 		if firstKeyExchange := t.sessionID == nil; firstKeyExchange {
-			msg.KexAlgos = make([]string, 0, len(t.config.KeyExchanges)+1)
-			msg.KexAlgos = append(msg.KexAlgos, t.config.KeyExchanges...)
 			msg.KexAlgos = append(msg.KexAlgos, "ext-info-c")
+			msg.KexAlgos = append(msg.KexAlgos, kexStrictClient)
 		}
+
 	}
 
 	packet := Marshal(msg)
@@ -604,6 +639,13 @@ func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
 		return err
 	}
 
+	if t.sessionID == nil && ((isClient && contains(serverInit.KexAlgos, kexStrictServer)) || (!isClient && contains(clientInit.KexAlgos, kexStrictClient))) {
+		t.strictMode = true
+		if err := t.conn.setStrictMode(); err != nil {
+			return err
+		}
+	}
+
 	// We don't send FirstKexFollows, but we handle receiving it.
 	//
 	// RFC 4253 section 7 defines the kex and the agreement method for
@@ -679,6 +721,12 @@ func (t *handshakeTransport) enterKeyExchange(otherInitPacket []byte) error {
 		return unexpectedMessageError(msgNewKeys, packet[0])
 	}
 
+	if firstKeyExchange {
+		// Indicates to the transport that the first key exchange is completed
+		// after receiving SSH_MSG_NEWKEYS.
+		t.conn.setInitialKEXDone()
+	}
+
 	return nil
 }
 

programming_language: Go
filename: handshake_test.go
change_type: ModificationType.MODIFY
diff: @@ -395,6 +395,10 @@ func (n *errorKeyingTransport) readPacket() ([]byte, error) {
 	return n.packetConn.readPacket()
 }
 
+func (n *errorKeyingTransport) setStrictMode() error { return nil }
+
+func (n *errorKeyingTransport) setInitialKEXDone() {}
+
 func TestHandshakeErrorHandlingRead(t *testing.T) {
 	for i := 0; i < 20; i++ {
 		testHandshakeErrorHandlingN(t, i, -1, false)
@@ -710,3 +714,308 @@ func TestPickIncompatibleHostKeyAlgo(t *testing.T) {
 		t.Fatal("incompatible signer returned")
 	}
 }
+
+func TestStrictKEXResetSeqFirstKEX(t *testing.T) {
+	if runtime.GOOS == "plan9" {
+		t.Skip("see golang.org/issue/7237")
+	}
+
+	checker := &syncChecker{
+		waitCall: make(chan int, 10),
+		called:   make(chan int, 10),
+	}
+
+	checker.waitCall <- 1
+	trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr", false)
+	if err != nil {
+		t.Fatalf("handshakePair: %v", err)
+	}
+	<-checker.called
+
+	t.Cleanup(func() {
+		trC.Close()
+		trS.Close()
+	})
+
+	// Throw away the msgExtInfo packet sent during the handshake by the server
+	_, err = trC.readPacket()
+	if err != nil {
+		t.Fatalf("readPacket failed: %s", err)
+	}
+
+	// close the handshake transports before checking the sequence number to
+	// avoid races.
+	trC.Close()
+	trS.Close()
+
+	// check that the sequence number counters. We reset after msgNewKeys, but
+	// then the server immediately writes msgExtInfo, and we close the
+	// transports so we expect read 2, write 0 on the client and read 1, write 1
+	// on the server.
+	if trC.conn.(*transport).reader.seqNum != 2 || trC.conn.(*transport).writer.seqNum != 0 ||
+		trS.conn.(*transport).reader.seqNum != 1 || trS.conn.(*transport).writer.seqNum != 1 {
+		t.Errorf(
+			"unexpected sequence counters:\nclient: reader %d (expected 2), writer %d (expected 0)\nserver: reader %d (expected 1), writer %d (expected 1)",
+			trC.conn.(*transport).reader.seqNum,
+			trC.conn.(*transport).writer.seqNum,
+			trS.conn.(*transport).reader.seqNum,
+			trS.conn.(*transport).writer.seqNum,
+		)
+	}
+}
+
+func TestStrictKEXResetSeqSuccessiveKEX(t *testing.T) {
+	if runtime.GOOS == "plan9" {
+		t.Skip("see golang.org/issue/7237")
+	}
+
+	checker := &syncChecker{
+		waitCall: make(chan int, 10),
+		called:   make(chan int, 10),
+	}
+
+	checker.waitCall <- 1
+	trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr", false)
+	if err != nil {
+		t.Fatalf("handshakePair: %v", err)
+	}
+	<-checker.called
+
+	t.Cleanup(func() {
+		trC.Close()
+		trS.Close()
+	})
+
+	// Throw away the msgExtInfo packet sent during the handshake by the server
+	_, err = trC.readPacket()
+	if err != nil {
+		t.Fatalf("readPacket failed: %s", err)
+	}
+
+	// write and read five packets on either side to bump the sequence numbers
+	for i := 0; i < 5; i++ {
+		if err := trC.writePacket([]byte{msgRequestSuccess}); err != nil {
+			t.Fatalf("writePacket failed: %s", err)
+		}
+		if _, err := trS.readPacket(); err != nil {
+			t.Fatalf("readPacket failed: %s", err)
+		}
+		if err := trS.writePacket([]byte{msgRequestSuccess}); err != nil {
+			t.Fatalf("writePacket failed: %s", err)
+		}
+		if _, err := trC.readPacket(); err != nil {
+			t.Fatalf("readPacket failed: %s", err)
+		}
+	}
+
+	// Request a key exchange, which should cause the sequence numbers to reset
+	checker.waitCall <- 1
+	trC.requestKeyExchange()
+	<-checker.called
+
+	// write a packet on the client, and then read it, to verify the key change has actually happened, since
+	// the HostKeyCallback is called _during_ the handshake, so isn't actually indicative of the handshake
+	// finishing.
+	dummyPacket := []byte{99}
+	if err := trS.writePacket(dummyPacket); err != nil {
+		t.Fatalf("writePacket failed: %s", err)
+	}
+	if p, err := trC.readPacket(); err != nil {
+		t.Fatalf("readPacket failed: %s", err)
+	} else if !bytes.Equal(p, dummyPacket) {
+		t.Fatalf("unexpected packet: got %x, want %x", p, dummyPacket)
+	}
+
+	// close the handshake transports before checking the sequence number to
+	// avoid races.
+	trC.Close()
+	trS.Close()
+
+	if trC.conn.(*transport).reader.seqNum != 2 || trC.conn.(*transport).writer.seqNum != 0 ||
+		trS.conn.(*transport).reader.seqNum != 1 || trS.conn.(*transport).writer.seqNum != 1 {
+		t.Errorf(
+			"unexpected sequence counters:\nclient: reader %d (expected 2), writer %d (expected 0)\nserver: reader %d (expected 1), writer %d (expected 1)",
+			trC.conn.(*transport).reader.seqNum,
+			trC.conn.(*transport).writer.seqNum,
+			trS.conn.(*transport).reader.seqNum,
+			trS.conn.(*transport).writer.seqNum,
+		)
+	}
+}
+
+func TestSeqNumIncrease(t *testing.T) {
+	if runtime.GOOS == "plan9" {
+		t.Skip("see golang.org/issue/7237")
+	}
+
+	checker := &syncChecker{
+		waitCall: make(chan int, 10),
+		called:   make(chan int, 10),
+	}
+
+	checker.waitCall <- 1
+	trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: checker.Check}, "addr", false)
+	if err != nil {
+		t.Fatalf("handshakePair: %v", err)
+	}
+	<-checker.called
+
+	t.Cleanup(func() {
+		trC.Close()
+		trS.Close()
+	})
+
+	// Throw away the msgExtInfo packet sent during the handshake by the server
+	_, err = trC.readPacket()
+	if err != nil {
+		t.Fatalf("readPacket failed: %s", err)
+	}
+
+	// write and read five packets on either side to bump the sequence numbers
+	for i := 0; i < 5; i++ {
+		if err := trC.writePacket([]byte{msgRequestSuccess}); err != nil {
+			t.Fatalf("writePacket failed: %s", err)
+		}
+		if _, err := trS.readPacket(); err != nil {
+			t.Fatalf("readPacket failed: %s", err)
+		}
+		if err := trS.writePacket([]byte{msgRequestSuccess}); err != nil {
+			t.Fatalf("writePacket failed: %s", err)
+		}
+		if _, err := trC.readPacket(); err != nil {
+			t.Fatalf("readPacket failed: %s", err)
+		}
+	}
+
+	// close the handshake transports before checking the sequence number to
+	// avoid races.
+	trC.Close()
+	trS.Close()
+
+	if trC.conn.(*transport).reader.seqNum != 7 || trC.conn.(*transport).writer.seqNum != 5 ||
+		trS.conn.(*transport).reader.seqNum != 6 || trS.conn.(*transport).writer.seqNum != 6 {
+		t.Errorf(
+			"unexpected sequence counters:\nclient: reader %d (expected 7), writer %d (expected 5)\nserver: reader %d (expected 6), writer %d (expected 6)",
+			trC.conn.(*transport).reader.seqNum,
+			trC.conn.(*transport).writer.seqNum,
+			trS.conn.(*transport).reader.seqNum,
+			trS.conn.(*transport).writer.seqNum,
+		)
+	}
+}
+
+func TestStrictKEXUnexpectedMsg(t *testing.T) {
+	if runtime.GOOS == "plan9" {
+		t.Skip("see golang.org/issue/7237")
+	}
+
+	// Check that unexpected messages during the handshake cause failure
+	_, _, err := handshakePair(&ClientConfig{HostKeyCallback: func(hostname string, remote net.Addr, key PublicKey) error { return nil }}, "addr", true)
+	if err == nil {
+		t.Fatal("handshake should fail when there are unexpected messages during the handshake")
+	}
+
+	trC, trS, err := handshakePair(&ClientConfig{HostKeyCallback: func(hostname string, remote net.Addr, key PublicKey) error { return nil }}, "addr", false)
+	if err != nil {
+		t.Fatalf("handshake failed: %s", err)
+	}
+
+	// Check that ignore/debug pacekts are still ignored outside of the handshake
+	if err := trC.writePacket([]byte{msgIgnore}); err != nil {
+		t.Fatalf("writePacket failed: %s", err)
+	}
+	if err := trC.writePacket([]byte{msgDebug}); err != nil {
+		t.Fatalf("writePacket failed: %s", err)
+	}
+	dummyPacket := []byte{99}
+	if err := trC.writePacket(dummyPacket); err != nil {
+		t.Fatalf("writePacket failed: %s", err)
+	}
+
+	if p, err := trS.readPacket(); err != nil {
+		t.Fatalf("readPacket failed: %s", err)
+	} else if !bytes.Equal(p, dummyPacket) {
+		t.Fatalf("unexpected packet: got %x, want %x", p, dummyPacket)
+	}
+}
+
+func TestStrictKEXMixed(t *testing.T) {
+	// Test that we still support a mixed connection, where one side sends kex-strict but the other
+	// side doesn't.
+
+	a, b, err := netPipe()
+	if err != nil {
+		t.Fatalf("netPipe failed: %s", err)
+	}
+
+	var trC, trS keyingTransport
+
+	trC = newTransport(a, rand.Reader, true)
+	trS = newTransport(b, rand.Reader, false)
+	trS = addNoiseTransport(trS)
+
+	clientConf := &ClientConfig{HostKeyCallback: func(hostname string, remote net.Addr, key PublicKey) error { return nil }}
+	clientConf.SetDefaults()
+
+	v := []byte("version")
+	client := newClientTransport(trC, v, v, clientConf, "addr", a.RemoteAddr())
+
+	serverConf := &ServerConfig{}
+	serverConf.AddHostKey(testSigners["ecdsa"])
+	serverConf.AddHostKey(testSigners["rsa"])
+	serverConf.SetDefaults()
+
+	transport := newHandshakeTransport(trS, &serverConf.Config, []byte("version"), []byte("version"))
+	transport.hostKeys = serverConf.hostKeys
+	transport.publicKeyAuthAlgorithms = serverConf.PublicKeyAuthAlgorithms
+
+	readOneFailure := make(chan error, 1)
+	go func() {
+		if _, err := transport.readOnePacket(true); err != nil {
+			readOneFailure <- err
+		}
+	}()
+
+	// Basically sendKexInit, but without the kex-strict extension algorithm
+	msg := &kexInitMsg{
+		KexAlgos:                transport.config.KeyExchanges,
+		CiphersClientServer:     transport.config.Ciphers,
+		CiphersServerClient:     transport.config.Ciphers,
+		MACsClientServer:        transport.config.MACs,
+		MACsServerClient:        transport.config.MACs,
+		CompressionClientServer: supportedCompressions,
+		CompressionServerClient: supportedCompressions,
+		ServerHostKeyAlgos:      []string{KeyAlgoRSASHA256, KeyAlgoRSASHA512, KeyAlgoRSA},
+	}
+	packet := Marshal(msg)
+	// writePacket destroys the contents, so save a copy.
+	packetCopy := make([]byte, len(packet))
+	copy(packetCopy, packet)
+	if err := transport.pushPacket(packetCopy); err != nil {
+		t.Fatalf("pushPacket: %s", err)
+	}
+	transport.sentInitMsg = msg
+	transport.sentInitPacket = packet
+
+	if err := transport.getWriteError(); err != nil {
+		t.Fatalf("getWriteError failed: %s", err)
+	}
+	var request *pendingKex
+	select {
+	case err = <-readOneFailure:
+		t.Fatalf("server readOnePacket failed: %s", err)
+	case request = <-transport.startKex:
+		break
+	}
+
+	// We expect the following calls to fail if the side which does not support
+	// kex-strict sends unexpected/ignored packets during the handshake, even if
+	// the other side does support kex-strict.
+
+	if err := transport.enterKeyExchange(request.otherInit); err != nil {
+		t.Fatalf("enterKeyExchange failed: %s", err)
+	}
+	if err := client.waitSession(); err != nil {
+		t.Fatalf("client.waitSession: %v", err)
+	}
+}

programming_language: Go
filename: transport.go
change_type: ModificationType.MODIFY
diff: @@ -49,6 +49,9 @@ type transport struct {
 	rand      io.Reader
 	isClient  bool
 	io.Closer
+
+	strictMode     bool
+	initialKEXDone bool
 }
 
 // packetCipher represents a combination of SSH encryption/MAC
@@ -74,6 +77,18 @@ type connectionState struct {
 	pendingKeyChange chan packetCipher
 }
 
+func (t *transport) setStrictMode() error {
+	if t.reader.seqNum != 1 {
+		return errors.New("ssh: sequence number != 1 when strict KEX mode requested")
+	}
+	t.strictMode = true
+	return nil
+}
+
+func (t *transport) setInitialKEXDone() {
+	t.initialKEXDone = true
+}
+
 // prepareKeyChange sets up key material for a keychange. The key changes in
 // both directions are triggered by reading and writing a msgNewKey packet
 // respectively.
@@ -112,11 +127,12 @@ func (t *transport) printPacket(p []byte, write bool) {
 // Read and decrypt next packet.
 func (t *transport) readPacket() (p []byte, err error) {
 	for {
-		p, err = t.reader.readPacket(t.bufReader)
+		p, err = t.reader.readPacket(t.bufReader, t.strictMode)
 		if err != nil {
 			break
 		}
-		if len(p) == 0 || (p[0] != msgIgnore && p[0] != msgDebug) {
+		// in strict mode we pass through DEBUG and IGNORE packets only during the initial KEX
+		if len(p) == 0 || (t.strictMode && !t.initialKEXDone) || (p[0] != msgIgnore && p[0] != msgDebug) {
 			break
 		}
 	}
@@ -127,7 +143,7 @@ func (t *transport) readPacket() (p []byte, err error) {
 	return p, err
 }
 
-func (s *connectionState) readPacket(r *bufio.Reader) ([]byte, error) {
+func (s *connectionState) readPacket(r *bufio.Reader, strictMode bool) ([]byte, error) {
 	packet, err := s.packetCipher.readCipherPacket(s.seqNum, r)
 	s.seqNum++
 	if err == nil && len(packet) == 0 {
@@ -140,6 +156,9 @@ func (s *connectionState) readPacket(r *bufio.Reader) ([]byte, error) {
 			select {
 			case cipher := <-s.pendingKeyChange:
 				s.packetCipher = cipher
+				if strictMode {
+					s.seqNum = 0
+				}
 			default:
 				return nil, errors.New("ssh: got bogus newkeys message")
 			}
@@ -170,10 +189,10 @@ func (t *transport) writePacket(packet []byte) error {
 	if debugTransport {
 		t.printPacket(packet, true)
 	}
-	return t.writer.writePacket(t.bufWriter, t.rand, packet)
+	return t.writer.writePacket(t.bufWriter, t.rand, packet, t.strictMode)
 }
 
-func (s *connectionState) writePacket(w *bufio.Writer, rand io.Reader, packet []byte) error {
+func (s *connectionState) writePacket(w *bufio.Writer, rand io.Reader, packet []byte, strictMode bool) error {
 	changeKeys := len(packet) > 0 && packet[0] == msgNewKeys
 
 	err := s.packetCipher.writeCipherPacket(s.seqNum, w, rand, packet)
@@ -188,6 +207,9 @@ func (s *connectionState) writePacket(w *bufio.Writer, rand io.Reader, packet []
 		select {
 		case cipher := <-s.pendingKeyChange:
 			s.packetCipher = cipher
+			if strictMode {
+				s.seqNum = 0
+			}
 		default:
 			panic("ssh: no key material for msgNewKeys")
 		}

programming_language: Go
repo_url: https://github.com/jtesta/ssh-audit
commit_details: repo_url: https://github.com/jtesta/ssh-audit
author: Joe Testa
author_date: 2023-12-18 18:24:49-05:00
msg: Added test for the Terrapin vulnerability (CVE-2023-48795) (#227).
repository: repo_url: https://github.com/jtesta/ssh-audit
repo_name: jtesta/ssh-audit
description: SSH server & client security auditing (banner, key exchange, encryption, mac, compression, compatibility, security, etc)
repo_language: Python
owner: jtesta
file_changes: filename: README.md
change_type: ModificationType.MODIFY
diff: @@ -184,6 +184,7 @@ For convenience, a web front-end on top of the command-line tool is available at
  - In Ubuntu 22.04 client policy, moved host key types `sk-ssh-ed25519@openssh.com` and `ssh-ed25519` to the end of all certificate types.
  - Re-organized option host key types for OpenSSH 9.2 server policy to correspond with updated Debian 12 hardening guide.
  - Dropped support for Python 3.7 (EOL was reached in June 2023).
+ - Added test for the Terrapin message prefix truncation vulnerability ([CVE-2023-48795](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-48795)).
 
 ### v3.0.0 (2023-09-07)
  - Results from concurrent scans against multiple hosts are no longer improperly combined; bug discovered by [Adam Russell](https://github.com/thecliguy).

programming_language: Markdown
filename: ssh2_kexdb.py
change_type: ModificationType.MODIFY
diff: @@ -71,6 +71,8 @@ class SSH2_KexDB:  # pylint: disable=too-few-public-methods
     INFO_REMOVED_IN_OPENSSH69 = 'removed in OpenSSH 6.9: https://www.openssh.com/txt/release-6.9'
     INFO_REMOVED_IN_OPENSSH70 = 'removed in OpenSSH 7.0: https://www.openssh.com/txt/release-7.0'
     INFO_WITHDRAWN_PQ_ALG = 'the sntrup4591761 algorithm was withdrawn, as it may not provide strong post-quantum security'
+    INFO_EXTENSION_NEGOTIATION = 'pseudo-algorithm that denotes the peer supports RFC8308 extensions'
+    INFO_STRICT_KEX = 'pseudo-algorithm that denotes the peer supports a stricter key exchange method as a counter-measure to the Terrapin attack (CVE-2023-48795)'
 
     # Maintains a dictionary per calling thread that yields its own copy of MASTER_DB.  This prevents results from one thread polluting the results of another thread.
     DB_PER_THREAD: Dict[int, Dict[str, Dict[str, List[List[Optional[str]]]]]] = {}
@@ -154,8 +156,10 @@ class SSH2_KexDB:  # pylint: disable=too-few-public-methods
             'ecdh-sha2-wiRIU8TKjMZ418sMqlqtvQ==': [[], [FAIL_UNPROVEN]],  # sect283k1
             'ecdh-sha2-zD/b3hu/71952ArpUG4OjQ==': [[], [FAIL_UNPROVEN, FAIL_SMALL_ECC_MODULUS]],  # sect233k1
             'ecmqv-sha2': [[], [FAIL_UNPROVEN]],
-            'ext-info-c': [[]],  # Extension negotiation (RFC 8308)
-            'ext-info-s': [[]],  # Extension negotiation (RFC 8308)
+            'ext-info-c': [[], [], [], [INFO_EXTENSION_NEGOTIATION]],  # Extension negotiation (RFC 8308)
+            'ext-info-s': [[], [], [], [INFO_EXTENSION_NEGOTIATION]],  # Extension negotiation (RFC 8308)
+            'kex-strict-c-v00@openssh.com': [[], [], [], [INFO_STRICT_KEX]],  # Strict KEX marker (countermeasure for CVE-2023-48795).
+            'kex-strict-s-v00@openssh.com': [[], [], [], [INFO_STRICT_KEX]],  # Strict KEX marker (countermeasure for CVE-2023-48795).
 
             # The GSS kex algorithms get special wildcard handling, since they include variable base64 data after their standard prefixes.
             'gss-13.3.132.0.10-sha256-*': [[], [FAIL_UNKNOWN]],

programming_language: Python
filename: ssh_audit.py
change_type: ModificationType.MODIFY
diff: @@ -447,7 +447,7 @@ def output_info(out: OutputBuffer, software: Optional['Software'], client_audit:
         out.sep()
 
 
-def post_process_findings(banner: Optional[Banner], algs: Algorithms) -> List[str]:
+def post_process_findings(banner: Optional[Banner], algs: Algorithms, client_audit: bool) -> List[str]:
     '''Perform post-processing on scan results before reporting them to the user.  Returns a list of algorithms that should not be recommended'''
 
 
@@ -466,6 +466,45 @@ def post_process_findings(banner: Optional[Banner], algs: Algorithms) -> List[st
         # Ensure that this algorithm doesn't appear in the recommendations section since the user cannot control this OpenSSH bug.
         algorithm_recommendation_suppress_list.append('diffie-hellman-group-exchange-sha256')
 
+    # Check for the Terrapin vulnerability (CVE-2023-48795), and mark the vulnerable algorithms.
+    if algs.ssh2kex is not None and \
+       ((client_audit and 'kex-strict-c-v00@openssh.com' not in algs.ssh2kex.kex_algorithms) or (not client_audit and 'kex-strict-s-v00@openssh.com' not in algs.ssh2kex.kex_algorithms)):  # Strict KEX marker is not present.
+
+        def add_terrapin_warning(db: Dict[str, Dict[str, List[List[Optional[str]]]]], category: str, algorithm_name: str) -> None:
+            while len(db[category][algorithm_name]) < 3:
+                db[category][algorithm_name].append([])
+
+            db[category][algorithm_name][2].append("vulnerable to the Terrapin attack (CVE-2023-48795), allowing message prefix truncation")
+
+        db = SSH2_KexDB.get_db()
+
+        # Without the strict KEX marker, these algorithms are always vulnerable.
+        add_terrapin_warning(db, "enc", "chacha20-poly1305")
+        add_terrapin_warning(db, "enc", "chacha20-poly1305@openssh.com")
+
+        cbc_ciphers = []
+        etm_macs = []
+
+        # Find the list of CBC ciphers the peer supports.
+        ciphers_supported = algs.ssh2kex.client.encryption if client_audit else algs.ssh2kex.server.encryption
+        for cipher in ciphers_supported:
+            if cipher.endswith("-cbc"):
+                cbc_ciphers.append(cipher)
+
+        # Find the list of ETM MACs the peer supports.
+        macs_supported = algs.ssh2kex.client.mac if client_audit else algs.ssh2kex.server.mac
+        for mac in macs_supported:
+            if mac.endswith("-etm@openssh.com"):
+                etm_macs.append(mac)
+
+        # If at least one CBC cipher and at least one ETM MAC is supported, mark them all as vulnerable.
+        if len(cbc_ciphers) > 0 and len(etm_macs) > 0:
+            for cipher in cbc_ciphers:
+                add_terrapin_warning(db, "enc", cipher)
+
+            for mac in etm_macs:
+                add_terrapin_warning(db, "mac", mac)
+
     return algorithm_recommendation_suppress_list
 
 
@@ -478,7 +517,7 @@ def output(out: OutputBuffer, aconf: AuditConf, banner: Optional[Banner], header
     algs = Algorithms(pkm, kex)
 
     # Perform post-processing on the findings to make final adjustments before outputting the results.
-    algorithm_recommendation_suppress_list = post_process_findings(banner, algs)
+    algorithm_recommendation_suppress_list = post_process_findings(banner, algs, client_audit)
 
     with out:
         if print_target:

programming_language: Python
filename: test_ssh2.py
change_type: ModificationType.MODIFY
diff: @@ -164,7 +164,7 @@ class TestSSH2:
         self.audit(out, self._conf())
         out.write()
         lines = output_spy.flush()
-        assert len(lines) == 70
+        assert len(lines) == 83
 
     def test_ssh2_server_invalid_first_packet(self, output_spy, virtual_socket):
         vsocket = virtual_socket

programming_language: Python
repo_url: https://github.com/connectbot/sshlib
commit_details: repo_url: https://github.com/connectbot/sshlib
author: Kenny Root
author_date: 2023-12-18 14:02:55-08:00
msg: Implement kex-strict from OpenSSH

Implement's OpenSSH's mitigation for the Terrapin attack.
repository: repo_url: https://github.com/connectbot/sshlib
repo_name: connectbot/sshlib
description: ConnectBot's SSH library
repo_language: Java
owner: connectbot
file_changes: filename: KexManager.java
change_type: ModificationType.MODIFY
diff: @@ -103,6 +103,9 @@ public class KexManager
 	/** RFC 8308 Section 2 */
 	private static final String EXT_INFO_C = "ext-info-c";
 
+	private static final String KEX_STRICT_C_OPENSSH = "kex-strict-c-v00@openssh.com";
+	private static final String KEX_STRICT_S_OPENSSH = "kex-strict-s-v00@openssh.com";
+
 	private KexState kxs;
 	private int kexCount = 0;
 	private KeyMaterial km;
@@ -193,6 +196,19 @@ public class KexManager
 		return (a[0].equals(b[0]));
 	}
 
+	private boolean containsAlgo(String[] algos, String targetAlgo)
+	{
+		if (algos == null || targetAlgo == null)
+			return false;
+
+		for (String algo : algos) {
+			if (targetAlgo.equals(algo))
+				return true;
+		}
+
+		return false;
+	}
+
 	private boolean isGuessOK(KexParameters cpar, KexParameters spar)
 	{
 		if (cpar == null || spar == null)
@@ -214,6 +230,8 @@ public class KexManager
 		{
 			np.kex_algo = getFirstMatch(client.kex_algorithms, server.kex_algorithms);
 
+			np.isStrictKex = containsAlgo(server.kex_algorithms, KEX_STRICT_S_OPENSSH);
+
 			log.log(20, "kex_algo=" + np.kex_algo);
 
 			np.server_host_key_algo = getFirstMatch(client.server_host_key_algorithms,
@@ -304,13 +322,14 @@ public class KexManager
 	 */
 	private static void addExtraKexAlgorithms(CryptoWishList cwl) {
 		String[] oldKexAlgorithms = cwl.kexAlgorithms;
-		List<String> kexAlgorithms = new ArrayList<>(oldKexAlgorithms.length + 1);
+		List<String> kexAlgorithms = new ArrayList<>(oldKexAlgorithms.length + 2);
 		for (String algo : oldKexAlgorithms)
 		{
-			if (!algo.equals(EXT_INFO_C))
+			if (!algo.equals(EXT_INFO_C) && !algo.equals(KEX_STRICT_C_OPENSSH))
 				kexAlgorithms.add(algo);
 		}
 		kexAlgorithms.add(EXT_INFO_C);
+		kexAlgorithms.add(KEX_STRICT_C_OPENSSH);
 		cwl.kexAlgorithms = kexAlgorithms.toArray(new String[0]);
 	}
 
@@ -746,4 +765,8 @@ public class KexManager
 
 		throw new IllegalStateException("Unkown KEX method! (" + kxs.np.kex_algo + ")");
 	}
+
+	public boolean isStrictKex() {
+		return kxs.np.isStrictKex;
+	}
 }

programming_language: Java
filename: NegotiatedParameters.java
change_type: ModificationType.MODIFY
diff: @@ -9,6 +9,7 @@ package com.trilead.ssh2.transport;
 public class NegotiatedParameters
 {
 	public boolean guessOK;
+	public boolean isStrictKex;
 	public String kex_algo;
 	public String server_host_key_algo;
 	public String enc_algo_client_to_server;

programming_language: Java
filename: TransportConnection.java
change_type: ModificationType.MODIFY
diff: @@ -361,4 +361,18 @@ public class TransportConnection
 		can_recv_compress = true;
 		can_send_compress = true;
 	}
+
+	/**
+	 * Resets the send sequence number for MAC calculation.
+	 */
+	public void resetSendSequenceNumber() {
+		send_seq_number = 0;
+	}
+
+	/**
+	 * Resets the receive sequence number for MAC calculation.
+	 */
+	public void resetReceiveSequenceNumber() {
+		recv_seq_number = 0;
+	}
 }

programming_language: Java
filename: TransportManager.java
change_type: ModificationType.MODIFY
diff: @@ -122,10 +122,11 @@ public class TransportManager
 	int port;
 	Socket sock;
 
-	Object connectionSemaphore = new Object();
+	private final Object connectionSemaphore = new Object();
 
 	boolean flagKexOngoing = false;
 	boolean connectionClosed = false;
+	boolean firstKexFinished = false;
 
 	Throwable reasonClosedCause = null;
 
@@ -404,6 +405,8 @@ public class TransportManager
 	}
 
 	public void kexFinished() {
+		firstKexFinished = true;
+
 		synchronized (connectionSemaphore)
 		{
 			flagKexOngoing = false;
@@ -419,11 +422,15 @@ public class TransportManager
 	public void changeRecvCipher(BlockCipher bc, MAC mac)
 	{
 		tc.changeRecvCipher(bc, mac);
+		if (km.isStrictKex())
+			tc.resetReceiveSequenceNumber();
 	}
 
 	public void changeSendCipher(BlockCipher bc, MAC mac)
 	{
 		tc.changeSendCipher(bc, mac);
+		if (km.isStrictKex())
+			tc.resetSendSequenceNumber();
 	}
 
 	/**
@@ -531,38 +538,6 @@ public class TransportManager
 
 			int type = msg[0] & 0xff;
 
-			if (type == Packets.SSH_MSG_IGNORE)
-				continue;
-
-			if (type == Packets.SSH_MSG_DEBUG)
-			{
-				if (log.isEnabled())
-				{
-					TypesReader tr = new TypesReader(msg, 0, msglen);
-					tr.readByte();
-					tr.readBoolean();
-					StringBuffer debugMessageBuffer = new StringBuffer();
-					debugMessageBuffer.append(tr.readString("UTF-8"));
-
-					for (int i = 0; i < debugMessageBuffer.length(); i++)
-					{
-						char c = debugMessageBuffer.charAt(i);
-
-						if ((c >= 32) && (c <= 126))
-							continue;
-						debugMessageBuffer.setCharAt(i, '\uFFFD');
-					}
-
-					log.log(50, "DEBUG Message from remote: '" + debugMessageBuffer.toString() + "'");
-				}
-				continue;
-			}
-
-			if (type == Packets.SSH_MSG_UNIMPLEMENTED)
-			{
-				throw new IOException("Peer sent UNIMPLEMENTED message, that should not happen.");
-			}
-
 			if (type == Packets.SSH_MSG_DISCONNECT)
 			{
 				TypesReader tr = new TypesReader(msg, 0, msglen);
@@ -615,6 +590,46 @@ public class TransportManager
 				continue;
 			}
 
+			/*
+			 * Any other packet should not be used when kex-strict is enabled.
+			 */
+			if (!firstKexFinished && km.isStrictKex())
+			{
+				throw new IOException("Unexpected packet received when kex-strict enabled");
+			}
+
+			if (type == Packets.SSH_MSG_IGNORE)
+				continue;
+
+			if (type == Packets.SSH_MSG_DEBUG)
+			{
+				if (log.isEnabled())
+				{
+					TypesReader tr = new TypesReader(msg, 0, msglen);
+					tr.readByte();
+					tr.readBoolean();
+					StringBuffer debugMessageBuffer = new StringBuffer();
+					debugMessageBuffer.append(tr.readString("UTF-8"));
+
+					for (int i = 0; i < debugMessageBuffer.length(); i++)
+					{
+						char c = debugMessageBuffer.charAt(i);
+
+						if ((c >= 32) && (c <= 126))
+							continue;
+						debugMessageBuffer.setCharAt(i, '\uFFFD');
+					}
+
+					log.log(50, "DEBUG Message from remote: '" + debugMessageBuffer.toString() + "'");
+				}
+				continue;
+			}
+
+			if (type == Packets.SSH_MSG_UNIMPLEMENTED)
+			{
+				throw new IOException("Peer sent UNIMPLEMENTED message, that should not happen.");
+			}
+
 			if (type == Packets.SSH_MSG_USERAUTH_SUCCESS) {
 				tc.startCompression();
 			}

programming_language: Java
repo_url: https://github.com/mscdex/ssh2
commit_details: repo_url: https://github.com/mscdex/ssh2
author: Brian White
author_date: 2023-12-18 14:42:10-05:00
msg: lib: add strict key exchange mode support
repository: repo_url: https://github.com/mscdex/ssh2
repo_name: mscdex/ssh2
description: SSH2 client and server modules written in pure JavaScript for node.js
repo_language: JavaScript
owner: mscdex
file_changes: filename: Protocol.js
change_type: ModificationType.MODIFY
diff: @@ -218,11 +218,18 @@ class Protocol {
     if (typeof offer !== 'object' || offer === null) {
       offer = (this._server ? DEFAULT_KEXINIT_SERVER : DEFAULT_KEXINIT_CLIENT);
     } else if (offer.constructor !== KexInit) {
-      if (!this._server)
-        offer.kex = offer.kex.concat(['ext-info-c']);
+      if (this._server) {
+        offer.kex = offer.kex.concat(['kex-strict-s-v00@openssh.com']);
+      } else {
+        offer.kex = offer.kex.concat([
+          'ext-info-c',
+          'kex-strict-c-v00@openssh.com',
+        ]);
+      }
       offer = new KexInit(offer);
     }
     this._kex = undefined;
+    this._strictMode = undefined;
     this._kexinit = undefined;
     this._offer = offer;
     this._cipher = new NullCipher(0, this._onWrite);

programming_language: JavaScript
filename: kex.js
change_type: ModificationType.MODIFY
diff: @@ -232,13 +232,37 @@ function handleKexInit(self, payload) {
     clientList = localKex;
     remoteExtInfoEnabled = (serverList.indexOf('ext-info-s') !== -1);
   }
+  if (self._strictMode === undefined) {
+    if (self._server) {
+      self._strictMode =
+        (clientList.indexOf('kex-strict-c-v00@openssh.com') !== -1);
+    } else {
+      self._strictMode =
+        (serverList.indexOf('kex-strict-s-v00@openssh.com') !== -1);
+    }
+    // Note: We check for seqno of 1 instead of 0 since we increment before
+    //       calling the packet handler
+    if (self._strictMode) {
+      debug && debug('Handshake: strict KEX mode enabled');
+      if (self._decipher.inSeqno !== 1) {
+        if (debug)
+          debug('Handshake: KEXINIT not first packet in strict KEX mode');
+        return doFatalError(
+          self,
+          'Handshake failed: KEXINIT not first packet in strict KEX mode',
+          'handshake',
+          DISCONNECT_REASON.KEY_EXCHANGE_FAILED
+        );
+      }
+    }
+  }
   // Check for agreeable key exchange algorithm
   for (i = 0;
        i < clientList.length && serverList.indexOf(clientList[i]) === -1;
        ++i);
   if (i === clientList.length) {
     // No suitable match found!
-    debug && debug('Handshake: No matching key exchange algorithm');
+    debug && debug('Handshake: no matching key exchange algorithm');
     return doFatalError(
       self,
       'Handshake failed: no matching key exchange algorithm',
@@ -1236,6 +1260,8 @@ const createKeyExchange = (() => {
             'Inbound: NEWKEYS'
           );
           this._receivedNEWKEYS = true;
+          if (this._protocol._strictMode)
+            this._protocol._decipher.inSeqno = 0;
           ++this._step;
 
           return this.finish(!this._protocol._server && !this._hostVerified);
@@ -1756,11 +1782,20 @@ function onKEXPayload(state, payload) {
   payload = this._packetRW.read.read(payload);
 
   const type = payload[0];
+
+  if (!this._strictMode) {
+    switch (type) {
+      case MESSAGE.IGNORE:
+      case MESSAGE.UNIMPLEMENTED:
+      case MESSAGE.DEBUG:
+        if (!MESSAGE_HANDLERS)
+          MESSAGE_HANDLERS = require('./handlers.js');
+        return MESSAGE_HANDLERS[type](this, payload);
+    }
+  }
+
   switch (type) {
     case MESSAGE.DISCONNECT:
-    case MESSAGE.IGNORE:
-    case MESSAGE.UNIMPLEMENTED:
-    case MESSAGE.DEBUG:
       if (!MESSAGE_HANDLERS)
         MESSAGE_HANDLERS = require('./handlers.js');
       return MESSAGE_HANDLERS[type](this, payload);
@@ -1776,6 +1811,8 @@ function onKEXPayload(state, payload) {
       state.firstPacket = false;
       return handleKexInit(this, payload);
     default:
+      // Ensure packet is either an algorithm negotiation or KEX
+      // algorithm-specific packet
       if (type < 20 || type > 49) {
         return doFatalError(
           this,
@@ -1824,6 +1861,8 @@ function trySendNEWKEYS(kex) {
       kex._protocol._packetRW.write.finalize(packet, true)
     );
     kex._sentNEWKEYS = true;
+    if (kex._protocol._strictMode)
+      kex._protocol._cipher.outSeqno = 0;
   }
 }
 
@@ -1832,7 +1871,7 @@ module.exports = {
   kexinit,
   onKEXPayload,
   DEFAULT_KEXINIT_CLIENT: new KexInit({
-    kex: DEFAULT_KEX.concat(['ext-info-c']),
+    kex: DEFAULT_KEX.concat(['ext-info-c', 'kex-strict-c-v00@openssh.com']),
     serverHostKey: DEFAULT_SERVER_HOST_KEY,
     cs: {
       cipher: DEFAULT_CIPHER,
@@ -1848,7 +1887,7 @@ module.exports = {
     },
   }),
   DEFAULT_KEXINIT_SERVER: new KexInit({
-    kex: DEFAULT_KEX,
+    kex: DEFAULT_KEX.concat(['kex-strict-s-v00@openssh.com']),
     serverHostKey: DEFAULT_SERVER_HOST_KEY,
     cs: {
       cipher: DEFAULT_CIPHER,

programming_language: JavaScript
filename: server.js
change_type: ModificationType.MODIFY
diff: @@ -294,7 +294,11 @@ class Server extends EventEmitter {
     }
 
     const algorithms = {
-      kex: generateAlgorithmList(cfgAlgos.kex, DEFAULT_KEX, SUPPORTED_KEX),
+      kex: generateAlgorithmList(
+        cfgAlgos.kex,
+        DEFAULT_KEX,
+        SUPPORTED_KEX
+      ).concat(['kex-strict-s-v00@openssh.com']),
       serverHostKey: hostKeyAlgoOrder,
       cs: {
         cipher: generateAlgorithmList(

programming_language: JavaScript