T2 ckpt 10 follow-up: EDTL/CDB pre-flight + strict R2T TTT

Architect review findings 2026-04-21 (ckpt 10 Medium):

#1 EDTL trusted before CDB validation (memory amplification)
    collectWriteData allocated make([]byte, edtl) and issued R2T
    for the full EDTL before SCSIHandler ran the CDB's transfer-
    length check. A hostile peer could advertise a huge EDTL on
    a tiny WRITE(10) CDB to force an outsized buffer + R2T +
    Data-Out collection before rejection.

    Fix in session.handleSCSICmd: compute the CDB-authoritative
    expected byte count (cdbExpectedWriteBytes for WRITE(10))
    BEFORE entering collectWriteData. Mismatched EDTL returns
    CHECK CONDITION + SenseIllegalRequest + ASCInvalidFieldInCDB
    without any allocation or R2T. Unrecognized write opcodes
    fall through to the handler's own validation path.

#2 R2T-solicited Data-Out accepted TTT=0xFFFFFFFF
    collectWriteData had `|| pdu.TTT != 0xFFFFFFFF` exception
    that silently admitted the unsolicited marker after the
    target had issued an explicit R2T with TTT=1. Weakened the
    InitialR2T=Yes "solicited-only" discipline.

    Fix in collectWriteData: remove the 0xFFFFFFFF exception.
    Data-Out MUST echo the R2T's TTT exactly. Comment updated
    to explain why.

Low: narrowed the read-side comment on sendDataInWithStatus /
     handleSCSICmd to reflect the actual T2 ckpt 10 scope
     (single Data-In PDU with S-bit; read splitting deferred
     until an OS initiator exposes the need).

core/frontend/iscsi/t2_ckpt10_hardening_test.go (NEW, sw regression)

  TestT2Route_ISCSI_LargeWrite_EDTLCDBMismatch_RejectsWithoutAllocating:
    Builds a SCSI-Cmd with WRITE(10) transferLen=1 (512 B) but
    EDTL=128 MiB. Asserts:
      - Target reply opcode != R2T  (no R2T issued)
      - Target reply opcode == SCSI-Response with CHECK CONDITION
      - Sense key == IllegalRequest; ASC == InvalidFieldInCDB
      - Round-trip fits within 2s (no 128 MiB allocation attempt)
      - Backend.Write invocation count == 0 (pre-flight reject
        never reaches the handler)
    Uses a custom countingBackend wrapping RecordingBackend to
    pin the "backend never invoked" invariant.

  TestT2Route_ISCSI_LargeWrite_WrongTTT_OnDataOut_Rejected:
    4-block write; 1 block immediate, 3 blocks solicited. Reads
    the R2T, then sends Data-Out with TTT=0xFFFFFFFF (the
    unsolicited marker) instead of echoing the R2T's TTT.
    Asserts:
      - Next read from the client side surfaces an error (target
        closed the session)
      - Backend WriteCount == 0
    Pins the stop-rule: no silent weakening of the negotiated
    solicited-only discipline.

Tests green (no regressions):
  core/frontend/iscsi: 74 tests (was 72; +2 hardening regressions)
  All other packages:  unchanged.

Stop-rule audit: fixes stay inside ckpt 9/10 allowlist. No new
auth/digest/storage/authority paths, no stale W/R semantics
weakened.

Not addressed in this commit (documentation drift, QA-owned):
  - The QA audit file header on t2_v2port_qa_test.go still
    claims V3 "does not implement R2T" which became stale after
    ckpt 10. sw cannot modify a QA-owned file without Discovery
    Bridge — flagged to QA Owner for header update.
This commit is contained in:
wzcheng99 committed 2026-04-21 22:52:34 -07:00
1 parent 5115cfc554
commit 239f8e52bc
2 files changed
+281 -13

No files matched your search

+52 -13
View File
@@ -248,20 +248,39 @@ func (s *Session) handleTextReq(req *PDU) error {
// 2. Remaining bytes solicited via R2T + Data-Out PDUs
// (T2 ckpt 10 port — enables iscsiadm writes larger
// than FirstBurstLength).
// The full payload is dispatched to the SCSI handler once
// ExpectedDataTransferLength bytes are collected.
// EDTL is validated against the CDB's transfer length BEFORE
// any allocation / R2T is issued — otherwise a hostile
// initiator could inflate EDTL vs. CDB and force
// make([]byte, edtl) + solicited Data-Out collection before
// the SCSI layer's own bounds check runs (architect review
// 2026-04-21 ckpt 10 Medium finding).
//
// - READ (FlagR) / metadata: response data rides in one or
// more Data-In PDUs with the S-bit on the last. Small
// payloads fit in a single Data-In; large reads that exceed
// MaxRecvDataSegmentLength are split (MaxRecv defaults to
// 256 KiB, bigger than T2 contract-smoke payloads).
// - READ (FlagR) / metadata: response data rides in ONE
// Data-In PDU with the S-bit set. T2 ckpt 10 does NOT split
// reads across multiple Data-In PDUs (MaxRecvDataSegmentLength
// currently bounds the whole read at 256 KiB; larger reads
// exceed T2 contract-smoke payloads). Multi-Data-In splitting
// lands if an OS initiator needs it.
func (s *Session) handleSCSICmd(ctx context.Context, req *PDU) error {
cdb := req.CDB()
edtl := req.ExpectedDataTransferLength()
isWrite := req.OpSpecific1()&FlagW != 0
var dataOut []byte
if isWrite && edtl > 0 {
// Pre-flight EDTL vs CDB consistency check. For writes
// we recognize (WRITE(10)), compute the authoritative
// expected bytes and reject mismatches at CHECK CONDITION
// BEFORE allocating edtl bytes or issuing R2T. Writes
// using an opcode we don't recognize here fall through
// to the handler (which rejects Invalid Opcode).
if expected, ok := cdbExpectedWriteBytes(cdb, s.handler.BlockSize()); ok {
if edtl != expected {
return s.sendSCSIResponse(req, illegalRequest(
ASCInvalidFieldInCDB, 0x00,
"EDTL does not match CDB transfer length"))
}
}
collected, err := s.collectWriteData(req, edtl)
if err != nil {
return err
@@ -273,7 +292,6 @@ func (s *Session) handleSCSICmd(ctx context.Context, req *PDU) error {
dataOut = req.DataSegment
}
cdb := req.CDB()
result := s.handler.HandleCommand(ctx, cdb, dataOut)
if len(result.Data) > 0 {
@@ -282,6 +300,24 @@ func (s *Session) handleSCSICmd(ctx context.Context, req *PDU) error {
return s.sendSCSIResponse(req, result)
}
// cdbExpectedWriteBytes computes the data-transfer size in bytes
// a WRITE CDB advertises. For opcodes we don't handle as writes
// (or don't recognize yet), returns (_, false) so the caller
// falls through to the SCSI handler's own per-opcode validation.
//
// Kept as a narrow lookup rather than reaching into scsi.go
// because handleSCSICmd doesn't need to build a SCSIResult — it
// just needs to bound the pre-allocation. Expand as new write
// opcodes are added to scsi.go.
func cdbExpectedWriteBytes(cdb [16]byte, blockSize uint32) (uint32, bool) {
switch cdb[0] {
case ScsiWrite10:
transferLen := uint32(cdb[7])<<8 | uint32(cdb[8])
return transferLen * blockSize, true
}
return 0, false
}
// collectWriteData assembles the write payload from immediate
// data (carried in the SCSI-Cmd) + any Data-Out PDUs solicited
// via R2T. Returns the full edtl-sized buffer on success.
@@ -340,11 +376,14 @@ func (s *Session) collectWriteData(req *PDU, edtl uint32) ([]byte, error) {
if pdu.Opcode() != OpSCSIDataOut {
return nil, fmt.Errorf("expected Data-Out, got %s", OpcodeName(pdu.Opcode()))
}
if pdu.TargetTransferTag() != ttt && pdu.TargetTransferTag() != 0xFFFFFFFF {
// Initiators typically echo our TTT; 0xFFFFFFFF is
// also accepted for unsolicited Data-Out but we
// disable that via InitialR2T=Yes.
return nil, fmt.Errorf("Data-Out TTT=0x%08x does not match R2T TTT=0x%08x",
if pdu.TargetTransferTag() != ttt {
// R2T-solicited Data-Out MUST echo the target's TTT
// from the R2T. 0xFFFFFFFF signals unsolicited
// Data-Out, which we disable via InitialR2T=Yes —
// accepting it here would silently weaken the
// negotiated "solicited-only" discipline (architect
// review 2026-04-21 ckpt 10 Medium finding).
return nil, fmt.Errorf("Data-Out TTT=0x%08x does not echo R2T TTT=0x%08x",
pdu.TargetTransferTag(), ttt)
}
if pdu.DataSN() != nextDataSN {
@@ -0,0 +1,229 @@
// Ownership: sw regression tests for architect review 2026-04-21
// ckpt 10 Medium findings:
//
// #1 EDTL/CDB consistency check MUST run before the target
// allocates memory or issues R2T (was: alloc edtl bytes
// upfront, then discover mismatch only when SCSI handler
// validated CDB).
//
// #2 R2T-solicited Data-Out must reject TTT=0xFFFFFFFF
// (unsolicited marker) — previously accepted, weakening
// the InitialR2T=Yes negotiated discipline.
//
// Both tests drive a real in-process target via the existing
// Go test client; the second bypasses the normal test client's
// TTT echo to force the bad TTT over the wire.
package iscsi_test
import (
"context"
"net"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
)
// countingBackend wraps a RecordingBackend to expose how many
// times Write was invoked. Used to confirm a pre-flight EDTL
// rejection NEVER reaches the backend.
type countingBackend struct {
inner *testback.RecordingBackend
writes atomic.Int32
}
func newCountingBackend() *countingBackend {
return &countingBackend{
inner: testback.NewRecordingBackend(frontend.Identity{
VolumeID: "v1", ReplicaID: "r1",
}),
}
}
func (b *countingBackend) Identity() frontend.Identity { return b.inner.Identity() }
func (b *countingBackend) Close() error { return b.inner.Close() }
func (b *countingBackend) Read(ctx context.Context, off int64, p []byte) (int, error) {
return b.inner.Read(ctx, off, p)
}
func (b *countingBackend) Write(ctx context.Context, off int64, p []byte) (int, error) {
b.writes.Add(1)
return b.inner.Write(ctx, off, p)
}
func (b *countingBackend) WriteCallCount() int32 { return b.writes.Load() }
// Architect finding #1 (memory-amplification / protocol
// consistency): a SCSI-Cmd claiming EDTL wildly larger than the
// CDB's WRITE(10) transfer length MUST be rejected at CHECK
// CONDITION BEFORE any R2T or large buffer allocation. The
// backend MUST NOT be invoked at all.
func TestT2Route_ISCSI_LargeWrite_EDTLCDBMismatch_RejectsWithoutAllocating(t *testing.T) {
rec := newCountingBackend()
prov := testback.NewStaticProvider(rec)
tg := iscsi.NewTarget(iscsi.TargetConfig{
Listen: "127.0.0.1:0",
IQN: "iqn.2026-04.example.v3:v1",
VolumeID: "v1",
Provider: prov,
})
addr, err := tg.Start()
if err != nil {
t.Fatalf("Start: %v", err)
}
defer tg.Close()
cli := dialAndLogin(t, addr)
defer cli.logout(t)
// Build a WRITE(10) CDB asking for 1 block. The CDB
// authoritative transfer size is 1 * 512 = 512 bytes.
cdb := writeCDB10(0, 1)
// Construct a SCSI-Cmd with a GIANT EDTL of 128 MiB, not
// reflecting the CDB. Carry 512 bytes of immediate data so
// the target would need to solicit (128 MiB - 512) via R2T
// if it trusted EDTL without pre-flight validation.
req := &iscsi.PDU{}
req.SetOpcode(iscsi.OpSCSICmd)
req.SetOpSpecific1(iscsi.FlagF | iscsi.FlagW)
req.SetLUN(0)
req.SetInitiatorTaskTag(cli.itt)
cli.itt++
const hostileEDTL uint32 = 128 * 1024 * 1024
req.SetExpectedDataTransferLength(hostileEDTL)
req.SetCmdSN(cli.cmdSN)
cli.cmdSN++
req.SetCDB(cdb)
req.DataSegment = make([]byte, iscsi.DefaultBlockSize) // 1 block immediate
before := time.Now()
if err := iscsi.WritePDU(cli.conn, req); err != nil {
t.Fatalf("WritePDU: %v", err)
}
// Target must respond quickly with CHECK CONDITION, NOT
// issue R2T and wait for 128 MiB of Data-Out. Use a tight
// deadline; if we fall off we know the target tried to
// allocate/solicit.
_ = cli.conn.SetReadDeadline(time.Now().Add(2 * time.Second))
resp, err := iscsi.ReadPDU(cli.conn)
if err != nil {
t.Fatalf("ReadPDU (target should have rejected fast): %v", err)
}
elapsed := time.Since(before)
if elapsed > 2*time.Second {
t.Fatalf("target took %v to reject EDTL/CDB mismatch — expected fast fail", elapsed)
}
if resp.Opcode() == iscsi.OpR2T {
t.Fatal("target issued R2T on EDTL/CDB mismatch — memory-amplification vector open")
}
if resp.Opcode() != iscsi.OpSCSIResp {
t.Fatalf("expected CHECK CONDITION SCSI-Response, got %s", iscsi.OpcodeName(resp.Opcode()))
}
if resp.SCSIStatusByte() != iscsi.StatusCheckCondition {
t.Fatalf("status=0x%02x want CHECK CONDITION", resp.SCSIStatusByte())
}
// Sense data rides in the data segment as fixed-format.
if len(resp.DataSegment) < 14 {
t.Fatalf("response missing sense data: len=%d", len(resp.DataSegment))
}
senseKey := resp.DataSegment[2] & 0x0f
asc := resp.DataSegment[12]
if senseKey != iscsi.SenseIllegalRequest {
t.Fatalf("sense key=0x%02x want IllegalRequest", senseKey)
}
if asc != iscsi.ASCInvalidFieldInCDB {
t.Fatalf("ASC=0x%02x want InvalidFieldInCDB (0x24)", asc)
}
if rec.WriteCallCount() != 0 {
t.Fatalf("backend Write invoked %d times on pre-flight reject (must be 0)",
rec.WriteCallCount())
}
}
// Architect finding #2: R2T-solicited Data-Out with
// TTT=0xFFFFFFFF MUST be rejected (session closes with error).
// The negotiated InitialR2T=Yes discipline requires the
// initiator to echo the R2T's TTT exactly.
func TestT2Route_ISCSI_LargeWrite_WrongTTT_OnDataOut_Rejected(t *testing.T) {
rec := testback.NewRecordingBackend(frontend.Identity{VolumeID: "v1", ReplicaID: "r1"})
prov := testback.NewStaticProvider(rec)
tg := iscsi.NewTarget(iscsi.TargetConfig{
Listen: "127.0.0.1:0",
IQN: "iqn.2026-04.example.v3:v1",
VolumeID: "v1",
Provider: prov,
})
addr, err := tg.Start()
if err != nil {
t.Fatalf("Start: %v", err)
}
defer tg.Close()
cli := dialAndLogin(t, addr)
// 4-block write; 1 block immediate, 3 blocks solicited.
const blocks = 4
const immediateBlocks = 1
blockSize := int(iscsi.DefaultBlockSize)
payload := make([]byte, blocks*blockSize)
req := &iscsi.PDU{}
req.SetOpcode(iscsi.OpSCSICmd)
req.SetOpSpecific1(iscsi.FlagF | iscsi.FlagW)
req.SetLUN(0)
itt := cli.itt
req.SetInitiatorTaskTag(itt)
cli.itt++
req.SetExpectedDataTransferLength(uint32(len(payload)))
req.SetCmdSN(cli.cmdSN)
cli.cmdSN++
req.SetCDB(writeCDB10(0, blocks))
req.DataSegment = payload[:immediateBlocks*blockSize]
if err := iscsi.WritePDU(cli.conn, req); err != nil {
t.Fatalf("WritePDU(SCSI-Cmd): %v", err)
}
// Expect R2T. Read it but DELIBERATELY ignore the TTT it
// carries when we build the Data-Out.
_ = cli.conn.SetReadDeadline(time.Now().Add(3 * time.Second))
r2t, err := iscsi.ReadPDU(cli.conn)
if err != nil {
t.Fatalf("read R2T: %v", err)
}
if r2t.Opcode() != iscsi.OpR2T {
t.Fatalf("expected R2T, got %s", iscsi.OpcodeName(r2t.Opcode()))
}
// Build a Data-Out with the UNSOLICITED marker TTT=0xFFFFFFFF
// instead of echoing R2T.TargetTransferTag(). Target must
// reject.
out := &iscsi.PDU{}
out.SetOpcode(iscsi.OpSCSIDataOut)
out.SetOpSpecific1(iscsi.FlagF)
out.SetLUN(0)
out.SetInitiatorTaskTag(itt)
out.SetTargetTransferTag(0xFFFFFFFF) // WRONG — unsolicited marker
out.SetDataSN(0)
out.SetBufferOffset(r2t.BufferOffset())
out.DataSegment = payload[immediateBlocks*blockSize:]
if err := iscsi.WritePDU(cli.conn, out); err != nil {
t.Fatalf("WritePDU(Data-Out): %v", err)
}
// Target should close the connection with a session error.
// Next read from our side surfaces EOF or a reset.
_ = cli.conn.SetReadDeadline(time.Now().Add(3 * time.Second))
_, readErr := iscsi.ReadPDU(cli.conn)
if readErr == nil {
t.Fatal("target accepted Data-Out with TTT=0xFFFFFFFF; R2T discipline weakened")
}
// Any connection-level error is acceptable: EOF, reset,
// broken pipe. The important thing is the target refused
// to commit the write.
_ = net.IPv4zero // silence unused-import linter
if rec.WriteCount() != 0 {
t.Fatalf("backend Write invoked %d times under bad-TTT rejection; expected 0",
rec.WriteCount())
}
_ = cli.conn.Close()
}