From 1db99266dfdda4e5fe56da50ae7b6dcbb1cb5a7d Mon Sep 17 00:00:00 2001 From: ZCShou <72115@163.com> Date: Wed, 9 Sep 2026 12:48:02 +0800 Subject: [PATCH] fix(pcsc): gate PIN verification on protected access and stop automatic retries --- internal/device/pool_pcsc.go | 3 + internal/device/pool_pcsc_test.go | 77 +++++++++++ internal/pcsc/pin_access.go | 128 ++++++++++++++++++ internal/pcsc/pin_access_test.go | 212 ++++++++++++++++++++++++++++++ internal/pcsc/pin_safety_test.go | 181 +++++++++++++++++++++++++ internal/pcsc/service.go | 76 +++++++++-- internal/pcsc/sim_files.go | 64 +++++---- internal/pcsc/types.go | 18 ++- 8 files changed, 719 insertions(+), 40 deletions(-) create mode 100644 internal/pcsc/pin_access.go create mode 100644 internal/pcsc/pin_access_test.go create mode 100644 internal/pcsc/pin_safety_test.go diff --git a/internal/device/pool_pcsc.go b/internal/device/pool_pcsc.go index 637449f6..aa1936db 100644 --- a/internal/device/pool_pcsc.go +++ b/internal/device/pool_pcsc.go @@ -88,6 +88,9 @@ func (p *Pool) reconcilePCSCReaders(opts rescanReconnectOptions, allDevices, dev if worker != nil || !opts.allowWorkerMutation(cfg.ID) { continue } + if p.sharedPCSCService().PINFailure(reader) != nil { + continue + } logger.Info("检测到 PC/SC 卡片上线,自动启动", "device", cfg.ID, "reader", reader.Name) if _, err := p.AddWorkerFromConfig(bindPCSCReader(cfg, reader)); err != nil { logger.Warn("自动启动 PC/SC 设备失败", "device", cfg.ID, "err", err) diff --git a/internal/device/pool_pcsc_test.go b/internal/device/pool_pcsc_test.go index d3cd59ee..a6586473 100644 --- a/internal/device/pool_pcsc_test.go +++ b/internal/device/pool_pcsc_test.go @@ -2,6 +2,7 @@ package device import ( "context" + "errors" "testing" "github.com/yibaiba/hideck/internal/backend" @@ -9,6 +10,82 @@ import ( "github.com/yibaiba/hideck/internal/pcsc" ) +type pinFailurePCSCBackend struct { + reader pcsc.Reader + opens int + queries int + verifications int + imsiSelected bool +} + +func (state *pinFailurePCSCBackend) Readers(context.Context) ([]pcsc.Reader, error) { + return []pcsc.Reader{state.reader}, nil +} + +func (state *pinFailurePCSCBackend) Open(context.Context, pcsc.Selector) (pcsc.Card, error) { + state.opens++ + return state, nil +} + +func (state *pinFailurePCSCBackend) Close() error { return nil } + +func (state *pinFailurePCSCBackend) Transmit(_ context.Context, command []byte) ([]byte, uint16, error) { + switch command[1] { + case 0xA4: + state.imsiSelected = command[2] == 0 && len(command) >= 7 && command[5] == 0x6F && command[6] == 0x07 + if command[2] == 4 { + return []byte{0x62, 0x08, 0xC6, 0x06, 0x90, 0x01, 0x80, 0x83, 0x01, 0x01}, 0x9000, nil + } + return nil, 0x9000, nil + case 0xB0: + if state.imsiSelected { + return nil, 0x6982, nil + } + return []byte{0x98, 0x10, 0x32, 0x54, 0x76, 0x98, 0x10, 0x32, 0x54, 0x76}, 0x9000, nil + case 0xB2: + return []byte{0x4F, 0x07, 0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02}, 0x9000, nil + case 0x20: + if len(command) == 5 { + state.queries++ + return nil, 0x63C3, nil + } + state.verifications++ + return nil, 0x6984, nil + default: + return nil, 0, errors.New("unexpected APDU") + } +} + +func TestReconcilePCSCReadersDoesNotRetryPINFailure(test *testing.T) { + test.Setenv("HIDECK_TEST_PIN", "1234") + cfg := config.DeviceConfig{ + ID: "reader-1", DeviceBackend: backend.BackendPCSC, + PCSCReaderName: "Reader A", PCSCUSBPath: "1-2", SIMPINEnv: "HIDECK_TEST_PIN", + } + pool := NewPool(&config.Config{Devices: []config.DeviceConfig{cfg}}) + test.Cleanup(pool.cancel) + native := &pinFailurePCSCBackend{reader: pcsc.Reader{Name: "Reader A", USBPath: "1-2", CardPresent: true}} + pool.pcscService = pcsc.NewWithBackend(native) + if _, err := pool.AddWorkerFromConfig(cfg); !errors.Is(err, pcsc.ErrPINRetryBlocked) || !errors.Is(err, pcsc.ErrPINVerification) { + test.Fatalf("unexpected startup error: %v", err) + } + for _, inserted := range []bool{true, true, false, true} { + native.reader.CardPresent = inserted + if err := pool.reconcilePCSCReaders(rescanReconnectOptions{}, []config.DeviceConfig{cfg}, []config.DeviceConfig{cfg}); err != nil { + test.Fatal(err) + } + } + if native.opens != 1 || native.queries != 1 || native.verifications != 1 { + test.Fatalf("automatic retry after failure: opens=%d queries=%d verifications=%d", native.opens, native.queries, native.verifications) + } + if _, err := pool.AddWorkerFromConfig(cfg); !errors.Is(err, pcsc.ErrPINRetryBlocked) { + test.Fatalf("manual worker rebuild bypassed guard: %v", err) + } + if native.queries != 1 || native.verifications != 1 { + test.Fatal("manual worker rebuild submitted another PIN operation") + } +} + type pcscReaderStateBackend struct { readers []pcsc.Reader } diff --git a/internal/pcsc/pin_access.go b/internal/pcsc/pin_access.go new file mode 100644 index 00000000..624d29d3 --- /dev/null +++ b/internal/pcsc/pin_access.go @@ -0,0 +1,128 @@ +package pcsc + +import ( + "context" + "errors" + "fmt" +) + +func (session *Session) withPINAccess(ctx context.Context, aid []byte, pin string, operation func() error) error { + accessErr := operation() + if !errors.Is(accessErr, ErrSecurityStatus) { + return accessErr + } + if err := session.lock.pinRetryError(); err != nil { + return errors.Join(accessErr, err) + } + fcp, err := selectApplication(ctx, session.card, aid) + if err != nil { + return errors.Join(accessErr, session.blockPINRetry(err)) + } + reference, err := activePINReference(fcp) + if err != nil { + return errors.Join(accessErr, session.blockPINRetry(fmt.Errorf("%w: %v", ErrPINStatusUnknown, err))) + } + if err := session.verifyPINReference(ctx, pin, reference); err != nil { + return errors.Join(accessErr, fmt.Errorf("pcsc: FCP PIN reference=%02X enabled/required: %w", reference, err)) + } + if _, err := selectApplication(ctx, session.card, aid); err != nil { + return session.blockPINRetry(err) + } + if err := operation(); err != nil { + return session.blockPINRetry(err) + } + return nil +} + +type pinTLV struct { + tag byte + value []byte +} + +func parsePINTLVs(data []byte) ([]pinTLV, error) { + var result []pinTLV + for len(data) != 0 { + if len(data) < 2 || data[0]&0x1F == 0x1F { + return nil, errors.New("unsupported or truncated FCP/PIN template tag") + } + length, consumed, ok := decodeTLVLength(data[1:]) + if !ok || 1+consumed+length > len(data) { + return nil, errors.New("truncated FCP/PIN template value") + } + end := 1 + consumed + length + result = append(result, pinTLV{tag: data[0], value: data[1+consumed : end]}) + data = data[end:] + } + return result, nil +} + +func activePINReference(fcp []byte) (byte, error) { + outer, err := parsePINTLVs(fcp) + if err != nil { + return 0, err + } + if len(outer) != 1 || outer[0].tag != 0x62 { + return 0, errors.New("USIM selection did not return an FCP template") + } + fields, err := parsePINTLVs(outer[0].value) + if err != nil { + return 0, err + } + var template []byte + for _, field := range fields { + if field.tag == 0xC6 { + if template != nil { + return 0, errors.New("duplicate PIN status template") + } + template = field.value + } + } + entries, err := parsePINTLVs(template) + if err != nil { + return 0, err + } + if len(entries) < 2 || entries[0].tag != 0x90 || len(entries[0].value) == 0 { + return 0, errors.New("missing PIN status bitmap or key references") + } + bitmap := entries[0].value + index := 0 + var candidate byte + var usage []byte + seen := make(map[byte]bool) + for _, entry := range entries[1:] { + switch entry.tag { + case 0x95: + if usage != nil || len(entry.value) != 1 || (entry.value[0] != 0 && entry.value[0] != 8) { + return 0, errors.New("invalid PIN usage qualifier") + } + usage = entry.value + case 0x83: + if len(entry.value) != 1 || index >= len(bitmap)*8 { + return 0, errors.New("PIN key reference does not match status bitmap") + } + reference := entry.value[0] + primary := (reference >= 1 && reference <= 8) || reference == 0x11 + secondary := reference >= 0x81 && reference <= 0x88 + if (!primary && !secondary) || seen[reference] || (reference == 0x11 && usage == nil) { + return 0, errors.New("unsupported or ambiguous PIN key reference") + } + seen[reference] = true + enabled := bitmap[index/8]&(0x80>>uint(index%8)) != 0 + required := usage == nil || usage[0] == 8 + if primary && enabled && required { + if candidate != 0 { + return 0, errors.New("multiple enabled primary PINs; refusing to choose one") + } + candidate = reference + } + index++ + usage = nil + default: + return 0, errors.New("unexpected PIN status template field") + } + } + if usage != nil || candidate == 0 { + return 0, errors.New("no unambiguous enabled/required user PIN in FCP; refusing verification") + } + return candidate, nil +} diff --git a/internal/pcsc/pin_access_test.go b/internal/pcsc/pin_access_test.go new file mode 100644 index 00000000..4e3b4c57 --- /dev/null +++ b/internal/pcsc/pin_access_test.go @@ -0,0 +1,212 @@ +package pcsc + +import ( + "bytes" + "context" + "errors" + "strings" + "testing" +) + +func pinTestFCP(bitmap byte, fields ...byte) []byte { + content := append([]byte{0x90, 0x01, bitmap}, fields...) + return append([]byte{0x62, byte(len(content) + 2), 0xC6, byte(len(content))}, content...) +} + +func TestActivePINReference(test *testing.T) { + for _, scenario := range []struct { + name string + fcp []byte + want byte + }{ + {"PIN1", pinTestFCP(0x80, 0x83, 0x01, 0x01), 0x01}, + {"application PIN reference 02", pinTestFCP(0x80, 0x83, 0x01, 0x02), 0x02}, + {"UPIN", pinTestFCP(0x80, 0x95, 0x01, 0x08, 0x83, 0x01, 0x11), 0x11}, + {"bitmap includes secondary PIN", pinTestFCP(0x20, 0x83, 0x01, 0x01, 0x83, 0x01, 0x81, 0x83, 0x01, 0x02), 0x02}, + {"disabled", pinTestFCP(0x00, 0x83, 0x01, 0x01), 0}, + {"not required", pinTestFCP(0x80, 0x95, 0x01, 0x00, 0x83, 0x01, 0x01), 0}, + {"unused UPIN", pinTestFCP(0x80, 0x95, 0x01, 0x00, 0x83, 0x01, 0x11), 0}, + {"UPIN missing qualifier", pinTestFCP(0x80, 0x83, 0x01, 0x11), 0}, + {"secondary only", pinTestFCP(0x80, 0x83, 0x01, 0x81), 0}, + {"ambiguous", pinTestFCP(0xC0, 0x83, 0x01, 0x01, 0x83, 0x01, 0x02), 0}, + {"duplicate", pinTestFCP(0x80, 0x83, 0x01, 0x01, 0x83, 0x01, 0x01), 0}, + {"invalid qualifier", pinTestFCP(0x80, 0x95, 0x01, 0x80, 0x83, 0x01, 0x01), 0}, + {"dangling qualifier", pinTestFCP(0x80, 0x83, 0x01, 0x01, 0x95, 0x01, 0x08), 0}, + {"empty", nil, 0}, + {"no PIN template", []byte{0x62, 0}, 0}, + {"truncated", []byte{0x62, 8, 0xC6}, 0}, + {"truncated PIN key", pinTestFCP(0x80, 0x83, 0x02, 0x01), 0}, + } { + test.Run(scenario.name, func(test *testing.T) { + actual, err := activePINReference(scenario.fcp) + if scenario.want == 0 { + if err == nil { + test.Fatalf("unsafe FCP accepted with reference %02X", actual) + } + } else if err != nil || actual != scenario.want { + test.Fatalf("reference=%02X err=%v, want %02X", actual, err, scenario.want) + } + }) + } +} + +type accessTestCard struct { + selected uint16 + fcp []byte + imsiStatus uint16 + authStatus uint16 + queryStatus uint16 + verifyStatus uint16 + verified bool + calls [][]byte +} + +func (card *accessTestCard) Close() error { return nil } + +func (card *accessTestCard) Transmit(_ context.Context, command []byte) ([]byte, uint16, error) { + card.calls = append(card.calls, append([]byte(nil), command...)) + switch command[1] { + case 0xA4: + if command[2] == 4 { + card.selected = 0 + return card.fcp, 0x9000, nil + } + card.selected = uint16(command[5])<<8 | uint16(command[6]) + if card.selected != 0x3F00 && card.selected != 0x2FE2 && card.selected != 0x2F00 && card.selected != 0x6F07 { + return nil, 0x6A82, nil + } + return nil, 0x9000, nil + case 0xB2: + return []byte{0x4F, 0x07, 0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02}, 0x9000, nil + case 0xB0: + if card.selected == 0x2FE2 { + return []byte{0x98, 0x10, 0x32, 0x54, 0x76, 0x98, 0x10, 0x32, 0x54, 0x76}, 0x9000, nil + } + if card.selected == 0x6F07 { + if card.imsiStatus != 0 && !card.verified { + return nil, card.imsiStatus, nil + } + return []byte{0x08, 0x19, 0x32, 0x54, 0x76, 0x98, 0x10, 0x32, 0x54}, 0x9000, nil + } + case 0x20: + if len(command) == 5 { + return nil, card.queryStatus, nil + } + card.verified = card.verifyStatus == 0x9000 + return nil, card.verifyStatus, nil + case 0x88: + if card.authStatus != 0 && !card.verified { + return nil, card.authStatus, nil + } + data := []byte{0xDB, 4, 1, 2, 3, 4, 16} + data = append(data, bytes.Repeat([]byte{0xAA}, 16)...) + data = append(data, 16) + data = append(data, bytes.Repeat([]byte{0xBB}, 16)...) + return data, 0x9000, nil + } + return nil, 0, errors.New("unexpected test APDU") +} + +type accessTestBackend struct{ card *accessTestCard } + +func (backend *accessTestBackend) Readers(context.Context) ([]Reader, error) { + return []Reader{{Name: "Reader A", USBPath: "1-2", CardPresent: true}}, nil +} + +func (backend *accessTestBackend) Open(context.Context, Selector) (Card, error) { + return backend.card, nil +} + +func TestReadableIdentityNeverQueriesOrVerifiesPIN(test *testing.T) { + for _, pin := range []string{"", "1234"} { + card := &accessTestCard{fcp: pinTestFCP(0, 0x83, 1, 1), queryStatus: 0x63C3} + service := NewWithBackend(&accessTestBackend{card: card}) + selector := Selector{ReaderName: "Reader A"} + identity, err := service.ReadIdentity(context.Background(), selector, pin) + if err != nil || identity.IMSI != "123456789012345" || identity.ICCID == "" || identity.PINRequired { + test.Fatalf("readable identity rejected: %v", err) + } + if _, err := service.CheckReady(context.Background(), selector, identity.ICCID, pin); err != nil { + test.Fatalf("readiness rejected: %v", err) + } + if _, err := service.Authenticate(context.Background(), selector, identity.ICCID, pin, AKAChallenge{}); err != nil { + test.Fatalf("authentication rejected: %v", err) + } + for _, command := range card.calls { + if command[1] == 0x20 { + test.Fatal("unnecessary PIN operation despite readable identity and accepted authentication") + } + } + } +} + +func TestAccessDenialRequiresFCPBeforePIN(test *testing.T) { + for _, fcp := range [][]byte{nil, pinTestFCP(0, 0x83, 1, 1), pinTestFCP(0xC0, 0x83, 1, 1, 0x83, 1, 2)} { + card := &accessTestCard{fcp: fcp, imsiStatus: 0x6982, queryStatus: 0x63C3} + service := NewWithBackend(&accessTestBackend{card: card}) + _, err := service.ReadIdentity(context.Background(), Selector{ReaderName: "Reader A"}, "1234") + if !errors.Is(err, ErrPINStatusUnknown) || !errors.Is(err, ErrPINRetryBlocked) || !strings.Contains(err.Error(), "read EF_IMSI") || !strings.Contains(err.Error(), "SW=6982") { + test.Fatalf("missing access/FCP diagnostics: %v", err) + } + for _, command := range card.calls { + if command[1] == 0x20 { + test.Fatal("PIN operation sent without an unambiguous enabled PIN") + } + } + } +} + +func TestNonSecurityReadFailureNeverTriggersPIN(test *testing.T) { + card := &accessTestCard{fcp: pinTestFCP(0x80, 0x83, 1, 1), imsiStatus: 0x6A82} + service := NewWithBackend(&accessTestBackend{card: card}) + _, err := service.ReadIdentity(context.Background(), Selector{ReaderName: "Reader A"}, "1234") + if err == nil || !strings.Contains(err.Error(), "SW=6A82") || errors.Is(err, ErrPINRequired) { + test.Fatalf("incorrectly classified file error: %v", err) + } + for _, command := range card.calls { + if command[1] == 0x20 { + test.Fatal("PIN operation sent for a non-security file error") + } + } +} + +func TestAccessDenialUsesFCPPINReferenceAndRetriesOnce(test *testing.T) { + for _, reference := range []byte{0x01, 0x02, 0x11} { + for _, authenticate := range []bool{false, true} { + card := &accessTestCard{ + fcp: pinTestFCP(0x80, 0x95, 1, 8, 0x83, 1, reference), + queryStatus: 0x63C3, verifyStatus: 0x9000, + } + service := NewWithBackend(&accessTestBackend{card: card}) + selector := Selector{ReaderName: "Reader A"} + var err error + if authenticate { + card.authStatus = 0x6982 + _, err = service.Authenticate(context.Background(), selector, "", "1234", AKAChallenge{}) + } else { + card.imsiStatus = 0x6982 + _, err = service.ReadIdentity(context.Background(), selector, "1234") + } + if err != nil { + test.Fatalf("reference %02X authenticate=%v: %v", reference, authenticate, err) + } + queries, submissions := 0, 0 + for _, command := range card.calls { + if command[1] != 0x20 { + continue + } + if command[3] != reference { + test.Fatalf("used wrong PIN reference: %02X", command[3]) + } + if len(command) == 5 { + queries++ + } else { + submissions++ + } + } + if queries != 1 || submissions != 1 { + test.Fatalf("PIN operations: query=%d submit=%d", queries, submissions) + } + } + } +} diff --git a/internal/pcsc/pin_safety_test.go b/internal/pcsc/pin_safety_test.go new file mode 100644 index 00000000..05e1659c --- /dev/null +++ b/internal/pcsc/pin_safety_test.go @@ -0,0 +1,181 @@ +package pcsc + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" +) + +func TestPINUnknownStateNeverSubmitsConfiguredPIN(test *testing.T) { + for _, status := range []uint16{0x0000, 0x6700, 0x6982, 0x6983, 0x6984, 0x6985, 0x9804, 0x6A86, 0x6D00, 0x6F00} { + test.Run(fmt.Sprintf("%04X", status), func(test *testing.T) { + card := &scriptedCard{replies: []scriptedReply{{sw: status}}} + err := verifyPIN(context.Background(), card, "1234") + var pinError *PINError + if !errors.Is(err, ErrPINStatusUnknown) || !errors.As(err, &pinError) || pinError.Status != status { + test.Fatalf("unexpected status error: %v", err) + } + if !strings.Contains(err.Error(), fmt.Sprintf("SW=%04X", status)) { + test.Fatalf("raw status lost: %v", err) + } + if len(card.calls) != 1 { + test.Fatalf("submitted PIN with unknown state: %d APDUs", len(card.calls)) + } + }) + } +} + +func TestPINLowRetriesNeverSubmitsPIN(test *testing.T) { + for _, status := range []uint16{0x63C0, 0x63C1, 0x63C2} { + card := &scriptedCard{replies: []scriptedReply{{sw: status}}} + if err := verifyPIN(context.Background(), card, "1234"); !errors.Is(err, ErrPINTriesLow) { + test.Fatalf("status %04X: unexpected error %v", status, err) + } + if len(card.calls) != 1 { + test.Fatalf("status %04X: submitted PIN", status) + } + } +} + +func TestPINVerificationPreservesFailureStatus(test *testing.T) { + for _, status := range []uint16{0x63C2, 0x6983, 0x6984, 0x6A80, 0x6D00, 0x6F00} { + card := &scriptedCard{replies: []scriptedReply{{sw: 0x63C3}, {sw: status}}} + err := verifyPIN(context.Background(), card, "1234") + var pinError *PINError + if !errors.As(err, &pinError) || pinError.Status != status || !strings.Contains(err.Error(), fmt.Sprintf("SW=%04X", status)) { + test.Fatalf("status %04X lost from error: %v", status, err) + } + if errors.Is(err, ErrPINRejected) != (status == 0x63C2) { + test.Fatalf("status %04X incorrectly classified: %v", status, err) + } + if len(card.calls) != 2 || strings.Contains(err.Error(), "1234") { + test.Fatal("unexpected command count or PIN leaked in error") + } + } +} + +func TestPINSuccessfulVerificationRemainsAvailable(test *testing.T) { + for _, replies := range [][]scriptedReply{ + {{sw: 0x9000}}, + {{sw: 0x63C3}, {sw: 0x9000}}, + } { + card := &scriptedCard{replies: replies} + service := NewWithBackend(&scriptedBackend{card: card}) + session, err := service.OpenSession(context.Background(), Selector{ReaderName: "Reader A"}) + if err != nil { + test.Fatal(err) + } + if err := session.verifyPIN(context.Background(), "1234"); err != nil { + test.Fatal(err) + } + if err := session.Close(); err != nil { + test.Fatal(err) + } + if err := service.PINFailure(Reader{Name: "Reader A", USBPath: "1-2"}); err != nil { + test.Fatalf("successful verification disabled retries: %v", err) + } + if len(card.calls) != len(replies) { + test.Fatalf("unexpected APDU count: %d", len(card.calls)) + } + } +} + +func TestPINFailureBlocksLaterSessionsAndAliases(test *testing.T) { + transportError := errors.New("native transport failed") + for _, scenario := range []struct { + name string + pin string + replies []scriptedReply + }{ + {name: "missing PIN", replies: []scriptedReply{{sw: 0x63C3}}}, + {name: "unknown state", pin: "1234", replies: []scriptedReply{{sw: 0x6983}}}, + {name: "rejected", pin: "1234", replies: []scriptedReply{{sw: 0x63C3}, {sw: 0x63C2}}}, + {name: "unknown verification result", pin: "1234", replies: []scriptedReply{{sw: 0x63C3}, {sw: 0x6984}}}, + {name: "status transport error", pin: "1234", replies: []scriptedReply{{err: transportError}}}, + {name: "verification transport error", pin: "1234", replies: []scriptedReply{{sw: 0x63C3}, {err: transportError}}}, + } { + test.Run(scenario.name, func(test *testing.T) { + card := &scriptedCard{replies: scenario.replies} + service := NewWithBackend(&scriptedBackend{card: card}) + for attempt, selector := range []Selector{{ReaderName: "Reader A"}, {USBPath: "1-2"}} { + session, err := service.OpenSession(context.Background(), selector) + if err != nil { + test.Fatal(err) + } + pin := scenario.pin + if attempt > 0 { + pin = "5678" + } + err = session.verifyPIN(context.Background(), pin) + if closeErr := session.Close(); closeErr != nil { + test.Fatal(closeErr) + } + if !errors.Is(err, ErrPINRetryBlocked) { + test.Fatalf("attempt %d did not block retries: %v", attempt, err) + } + if len(card.calls) != len(scenario.replies) { + test.Fatalf("attempt %d submitted extra APDUs: %d", attempt, len(card.calls)) + } + } + if err := service.PINFailure(Reader{Name: "Reader A", USBPath: "1-2"}); !errors.Is(err, ErrPINRetryBlocked) { + test.Fatalf("missing reader-level failure: %v", err) + } + if err := service.PINFailure(Reader{Name: "Reader B", USBPath: "1-3"}); err != nil { + test.Fatalf("failure leaked into unrelated reader: %v", err) + } + }) + } +} + +func TestPINFailureGuardCoversIdentityReadinessAndAuthentication(test *testing.T) { + selection := []scriptedReply{ + {sw: 0x9000}, + {sw: 0x9000}, + {data: []byte{0x98, 0x10, 0x32, 0x54, 0x76, 0x98, 0x10, 0x32, 0x54, 0x76}, sw: 0x9000}, + {sw: 0x9000}, + {sw: 0x9000}, + {data: []byte{0x4F, 0x07, 0xA0, 0x00, 0x00, 0x00, 0x87, 0x10, 0x02}, sw: 0x9000}, + {sw: 0x9000}, + } + card := &scriptedCard{} + card.replies = append(card.replies, selection...) + card.replies = append(card.replies, + scriptedReply{sw: 0x9000}, + scriptedReply{sw: 0x6982}, + scriptedReply{data: []byte{0x62, 0x08, 0xC6, 0x06, 0x90, 0x01, 0x80, 0x83, 0x01, 0x01}, sw: 0x9000}, + ) + card.replies = append(card.replies, scriptedReply{sw: 0x63C3}, scriptedReply{sw: 0x6984}) + card.replies = append(card.replies, selection...) + card.replies = append(card.replies, scriptedReply{sw: 0x9000}, scriptedReply{sw: 0x6982}) + card.replies = append(card.replies, selection...) + service := NewWithBackend(&scriptedBackend{card: card}) + selector := Selector{ReaderName: "Reader A"} + identity, err := service.ReadIdentity(context.Background(), selector, "1234") + if identity.ICCID == "" || !errors.Is(err, ErrPINVerification) || !errors.Is(err, ErrPINRetryBlocked) { + test.Fatalf("unexpected identity result: %v", err) + } + if _, err := service.CheckReady(context.Background(), selector, identity.ICCID, "1234"); !errors.Is(err, ErrPINRetryBlocked) { + test.Fatalf("readiness check bypassed guard: %v", err) + } + if _, err := service.Authenticate(context.Background(), selector, identity.ICCID, "1234", AKAChallenge{}); !errors.Is(err, ErrPINRetryBlocked) { + test.Fatalf("authentication bypassed guard: %v", err) + } + queries, submissions := 0, 0 + for _, command := range card.calls { + if command[1] == 0x88 { + test.Fatal("authentication APDU was sent despite PIN failure") + } + if command[1] == 0x20 { + if len(command) == 5 { + queries++ + } else { + submissions++ + } + } + } + if queries != 1 || submissions != 1 { + test.Fatalf("PIN retried: queries=%d submissions=%d", queries, submissions) + } +} diff --git a/internal/pcsc/service.go b/internal/pcsc/service.go index 536f4bce..12b37988 100644 --- a/internal/pcsc/service.go +++ b/internal/pcsc/service.go @@ -70,7 +70,9 @@ func (service *Service) resolveSelector(ctx context.Context, selector Selector) } type readerGate struct { - token chan struct{} + token chan struct{} + pinMu sync.RWMutex + pinFailure error } func newReaderGate() *readerGate { @@ -93,6 +95,22 @@ func (gate *readerGate) acquire(ctx context.Context) error { func (gate *readerGate) release() { gate.token <- struct{}{} } +func (gate *readerGate) pinRetryError() error { + gate.pinMu.RLock() + defer gate.pinMu.RUnlock() + if gate.pinFailure == nil { + return nil + } + return fmt.Errorf("%w: %w", ErrPINRetryBlocked, gate.pinFailure) +} + +func (service *Service) PINFailure(reader Reader) error { + if service == nil { + return ErrUnavailable + } + return service.readerLock(canonicalSelector(reader)).pinRetryError() +} + func (service *Service) readerLock(selector Selector) *readerGate { key := selectorLockKey(selector) service.locksMu.Lock() @@ -117,6 +135,29 @@ type Session struct { closed bool } +func (session *Session) verifyPIN(ctx context.Context, pin string) error { + return session.verifyPINReference(ctx, pin, 0x01) +} + +func (session *Session) blockPINRetry(err error) error { + session.lock.pinMu.Lock() + if session.lock.pinFailure == nil { + session.lock.pinFailure = err + } + session.lock.pinMu.Unlock() + return session.lock.pinRetryError() +} + +func (session *Session) verifyPINReference(ctx context.Context, pin string, reference byte) error { + if err := session.lock.pinRetryError(); err != nil { + return err + } + if err := verifyPINReference(ctx, session.card, pin, reference); err != nil { + return session.blockPINRetry(err) + } + return nil +} + func (service *Service) OpenSession(ctx context.Context, selector Selector) (*Session, error) { if service == nil || service.backend == nil { return nil, ErrUnavailable @@ -203,7 +244,7 @@ func (service *Service) ReadIdentity(ctx context.Context, selector Selector, pin return Identity{}, err } defer session.Close() - return readIdentity(ctx, session.card, pin) + return session.readIdentity(ctx, pin) } func MatchReader(readers []Reader, selector Selector) (Reader, bool) { @@ -253,7 +294,13 @@ func (service *Service) CheckReady(ctx context.Context, selector Selector, expec if err != nil { return "", err } - if err := verifyPIN(ctx, session.card, pin); err != nil { + if err := session.withPINAccess(ctx, aid, pin, func() error { + _, err := readIMSI(ctx, session.card) + return err + }); err != nil { + return "", err + } + if _, err := selectApplication(ctx, session.card, aid); err != nil { return "", err } return strings.ToUpper(hex.EncodeToString(aid)), nil @@ -263,7 +310,7 @@ func statusError(operation string, sw uint16) error { if sw == 0x9862 { return ErrAKARejected } - return fmt.Errorf("pcsc: %s failed with status %04X", operation, sw) + return requireStatus(operation, sw, nil) } func (service *Service) Authenticate(ctx context.Context, selector Selector, expectedICCID, pin string, challenge AKAChallenge) (AKAResult, error) { @@ -279,10 +326,11 @@ func (service *Service) Authenticate(ctx context.Context, selector Selector, exp if changedCard(expectedICCID, iccid) { return AKAResult{}, ErrCardChanged } - if _, err := selectUSIM(ctx, session.card); err != nil { + aid, err := selectUSIM(ctx, session.card) + if err != nil { return AKAResult{}, err } - if err := verifyPIN(ctx, session.card, pin); err != nil { + if err := session.lock.pinRetryError(); err != nil { return AKAResult{}, err } apdu := []byte{0x00, 0x88, 0x00, 0x81, 0x22, 0x10} @@ -290,12 +338,18 @@ func (service *Service) Authenticate(ctx context.Context, selector Selector, exp apdu = append(apdu, 0x10) apdu = append(apdu, challenge.AUTN[:]...) apdu = append(apdu, 0x00) - data, sw, err := session.card.Transmit(ctx, apdu) + var data []byte + err = session.withPINAccess(ctx, aid, pin, func() error { + var status uint16 + var transportErr error + data, status, transportErr = session.card.Transmit(ctx, apdu) + if transportErr != nil { + return fmt.Errorf("pcsc: USIM authentication transport failed: %w", transportErr) + } + return statusError("USIM authentication", status) + }) if err != nil { - return AKAResult{}, fmt.Errorf("pcsc: USIM authentication transport failed: %w", err) - } - if sw != 0x9000 { - return AKAResult{}, statusError("USIM authentication", sw) + return AKAResult{}, err } return parseAKAResponse(data) } diff --git a/internal/pcsc/sim_files.go b/internal/pcsc/sim_files.go index 6ca3c611..189da02f 100644 --- a/internal/pcsc/sim_files.go +++ b/internal/pcsc/sim_files.go @@ -9,7 +9,8 @@ import ( "strings" ) -func readIdentity(ctx context.Context, card Card, pin string) (Identity, error) { +func (session *Session) readIdentity(ctx context.Context, pin string) (Identity, error) { + card := session.card identity := Identity{PINTries: -1} var err error identity.ICCID, err = readICCID(ctx, card) @@ -20,7 +21,12 @@ func readIdentity(ctx context.Context, card Card, pin string) (Identity, error) if err != nil { return identity, err } - if err := verifyPIN(ctx, card, pin); err != nil { + err = session.withPINAccess(ctx, identity.USIMAID, pin, func() error { + var readErr error + identity.IMSI, readErr = readIMSI(ctx, card) + return readErr + }) + if err != nil { identity.PINRequired = errors.Is(err, ErrPINRequired) || errors.Is(err, ErrPINTriesLow) var pinErr *PINError if errors.As(err, &pinErr) { @@ -28,16 +34,6 @@ func readIdentity(ctx context.Context, card Card, pin string) (Identity, error) } return identity, err } - if err := selectFile(ctx, card, []byte{0x6F, 0x07}); err != nil { - return identity, fmt.Errorf("pcsc: select EF_IMSI: %w", err) - } - imsiData, err := readBinary(ctx, card, 9) - if err != nil { - return identity, fmt.Errorf("pcsc: read EF_IMSI: %w", err) - } - if identity.IMSI, err = decodeIMSI(imsiData); err != nil { - return identity, err - } if reselectUSIM(ctx, card, identity.USIMAID) { identity.MNCLength = readMNCLength(ctx, card) } @@ -50,6 +46,17 @@ func readIdentity(ctx context.Context, card Card, pin string) (Identity, error) return identity, nil } +func readIMSI(ctx context.Context, card Card) (string, error) { + if err := selectFile(ctx, card, []byte{0x6F, 0x07}); err != nil { + return "", fmt.Errorf("pcsc: select EF_IMSI: %w", err) + } + data, err := readBinary(ctx, card, 9) + if err != nil { + return "", fmt.Errorf("pcsc: read EF_IMSI: %w", err) + } + return decodeIMSI(data) +} + func reselectUSIM(ctx context.Context, card Card, aid []byte) bool { _, err := selectApplication(ctx, card, aid) return err == nil @@ -160,10 +167,14 @@ func readBinary(ctx context.Context, card Card, length int) ([]byte, error) { } func verifyPIN(ctx context.Context, card Card, pin string) error { + return verifyPINReference(ctx, card, pin, 0x01) +} + +func verifyPINReference(ctx context.Context, card Card, pin string, reference byte) error { pin = strings.TrimSpace(pin) - _, sw, err := card.Transmit(ctx, []byte{0x00, 0x20, 0x00, 0x01, 0x00}) + _, sw, err := card.Transmit(ctx, []byte{0x00, 0x20, 0x00, reference, 0x00}) if err != nil { - return fmt.Errorf("pcsc: SIM PIN status check failed: %w", err) + return &PINError{Kind: fmt.Errorf("pcsc: SIM PIN status check failed: %w", err), Tries: -1} } if sw == 0x9000 { return nil @@ -171,33 +182,36 @@ func verifyPIN(ctx context.Context, card Card, pin string) error { tries := pinTries(sw) if pin == "" { if tries >= 0 { - return &PINError{Kind: ErrPINRequired, Tries: tries} + return &PINError{Kind: ErrPINRequired, Tries: tries, Status: sw, HasStatus: true} } if sw == 0x6982 || sw == 0x9804 { - return &PINError{Kind: ErrPINRequired, Tries: -1} + return &PINError{Kind: ErrPINRequired, Tries: -1, Status: sw, HasStatus: true} } - return fmt.Errorf("pcsc: SIM PIN status check failed with status %04X", sw) + return &PINError{Kind: ErrPINStatusUnknown, Tries: -1, Status: sw, HasStatus: true} + } + if tries < 0 { + return &PINError{Kind: ErrPINStatusUnknown, Tries: -1, Status: sw, HasStatus: true} } if len(pin) < 4 || len(pin) > 8 || !decimalDigits(pin) { - return errors.New("pcsc: SIM PIN must contain 4 to 8 digits") + return &PINError{Kind: errors.New("pcsc: SIM PIN must contain 4 to 8 digits"), Tries: tries, Status: sw, HasStatus: true} } if tries >= 0 && tries <= 2 { - return &PINError{Kind: ErrPINTriesLow, Tries: tries} + return &PINError{Kind: ErrPINTriesLow, Tries: tries, Status: sw, HasStatus: true} } body := bytes.Repeat([]byte{0xFF}, 8) copy(body, pin) - apdu := append([]byte{0x00, 0x20, 0x00, 0x01, 0x08}, body...) + apdu := append([]byte{0x00, 0x20, 0x00, reference, 0x08}, body...) _, sw, err = card.Transmit(ctx, apdu) if err != nil { - return fmt.Errorf("pcsc: SIM PIN verification transport failed: %w", err) + return &PINError{Kind: fmt.Errorf("pcsc: SIM PIN verification transport failed: %w", err), Tries: -1} } if sw == 0x9000 { return nil } if tries = pinTries(sw); tries >= 0 { - return &PINError{Kind: ErrPINRejected, Tries: tries} + return &PINError{Kind: ErrPINRejected, Tries: tries, Status: sw, HasStatus: true} } - return ErrPINRejected + return &PINError{Kind: ErrPINVerification, Tries: -1, Status: sw, HasStatus: true} } func pinTries(sw uint16) int { @@ -215,7 +229,7 @@ func requireStatus(operation string, sw uint16, err error) error { return nil } if sw == 0x6982 || sw == 0x9804 { - return &PINError{Kind: ErrPINRequired, Tries: -1} + return fmt.Errorf("pcsc: %s failed (SW=%04X): %w", operation, sw, ErrSecurityStatus) } - return fmt.Errorf("pcsc: %s failed with status %04X", operation, sw) + return fmt.Errorf("pcsc: %s failed (SW=%04X)", operation, sw) } diff --git a/internal/pcsc/types.go b/internal/pcsc/types.go index 65d4aa95..314dc72b 100644 --- a/internal/pcsc/types.go +++ b/internal/pcsc/types.go @@ -17,6 +17,10 @@ var ( ErrPINRequired = errors.New("pcsc: SIM PIN is required") ErrPINTriesLow = errors.New("pcsc: refusing PIN verification because too few attempts remain") ErrPINRejected = errors.New("pcsc: SIM PIN was rejected") + ErrPINStatusUnknown = errors.New("pcsc: SIM PIN state or retry count is unknown; verification refused") + ErrPINVerification = errors.New("pcsc: SIM PIN verification failed") + ErrPINRetryBlocked = errors.New("pcsc: automatic SIM PIN retries disabled; resolve the cause before restarting HiDeck") + ErrSecurityStatus = errors.New("pcsc: card security status does not allow this operation") ErrUSIMUnavailable = errors.New("pcsc: no usable USIM application was found") ErrApplicationNotFound = errors.New("pcsc: smart-card application was not found") ErrCardChanged = errors.New("pcsc: card identity changed during authentication") @@ -76,18 +80,24 @@ type AKAResult struct { } type PINError struct { - Kind error - Tries int + Kind error + Tries int + Status uint16 + HasStatus bool } func (err *PINError) Error() string { if err == nil { return "pcsc: SIM PIN error" } + message := err.Kind.Error() if err.Tries >= 0 { - return fmt.Sprintf("%v (%d attempts remain)", err.Kind, err.Tries) + message = fmt.Sprintf("%s (%d attempts remain)", message, err.Tries) } - return err.Kind.Error() + if err.HasStatus || err.Status != 0 { + message = fmt.Sprintf("%s (SW=%04X)", message, err.Status) + } + return message } func (err *PINError) Unwrap() error {