@@ -601,22 +601,79 @@ INLINE static int IsMessageAllowedServer(WOLFSSH *ssh, byte msg)
601601 /* Only the server should send these messages, never receive. */
602602 if (msg == MSGID_SERVICE_ACCEPT) {
603603 WLOG(WS_LOG_DEBUG, "Message ID %u not allowed by %s %s",
604- msg, "client", "ever");
604+ msg, "server", "ever");
605+ ssh->error = WS_MSGID_NOT_ALLOWED_E;
605606 return 0;
606607 }
607608
609+ if (msg == MSGID_SERVICE_REQUEST) {
610+ if (ssh->acceptState == ACCEPT_KEYED) {
611+ return 1;
612+ }
613+ else {
614+ WLOG(WS_LOG_DEBUG, "Message ID %u not allowed by %s %s",
615+ msg, "server", "after starting user auth");
616+ return 0;
617+ }
618+ }
619+
608620 /* Transport Layer Generic messages are always allowed. */
609621 if (MSGIDLIMIT_TRANS_GEN(msg)) {
610622 return 1;
611623 }
612624
625+ /* Is KEX complete? */
626+ if (MSGIDLIMIT_TRANS(msg)) {
627+ if (ssh->isKeying & WOLFSSH_PEER_IS_KEYING) {
628+ /* MSGID_KEXINIT not allowed when keying. */
629+ if (msg == MSGID_KEXINIT) {
630+ WLOG(WS_LOG_DEBUG, "Message ID %u not allowed by %s %s",
631+ msg, "server", "when keying");
632+ ssh->error = WS_REKEYING;
633+ return 0;
634+ }
635+
636+ /* Error if expecting a specific message and didn't receive. */
637+ if (ssh->handshake && ssh->handshake->expectMsgId != MSGID_NONE) {
638+ /* The explicit expectMsgId check supersedes the old
639+ * IsMessageAllowedKeying() stub for rekey filtering. */
640+ if (msg != ssh->handshake->expectMsgId) {
641+ WLOG(WS_LOG_DEBUG,
642+ "Message ID %u not the expected message %u",
643+ msg, ssh->handshake->expectMsgId);
644+ ssh->error = WS_REKEYING;
645+ return 0;
646+ }
647+ else {
648+ /* Got the expected message, clear expectation. */
649+ ssh->handshake->expectMsgId = MSGID_NONE;
650+ return 1;
651+ }
652+ }
653+ }
654+ else {
655+ /* MSGID_KEXINIT only allowed when not keying. */
656+ if (msg == MSGID_KEXINIT) {
657+ return 1;
658+ }
659+
660+ /* All other transport KEX and ALGO messages are not allowed
661+ * when not keying. */
662+ WLOG(WS_LOG_DEBUG, "Message ID %u not allowed by %s %s",
663+ msg, "server", "when not keying");
664+ ssh->error = WS_MSGID_NOT_ALLOWED_E;
665+ return 0;
666+ }
667+ }
668+
613669 /* Has client userauth started? */
614670 /* Allows the server to receive up to KEXDH GEX Request during KEX. */
615671 if (ssh->acceptState < ACCEPT_KEYED) {
616672 if (msg > MSGID_KEXDH_GEX_REQUEST) {
617673 return 0;
618674 }
619675 }
676+
620677 /* Is server userauth complete? */
621678 if (ssh->acceptState < ACCEPT_SERVER_USERAUTH_SENT) {
622679 /* The server should only receive the user auth request message,
0 commit comments