Something went wrong. Try again.
ACME Service and Go API for PicoHSM
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303package ccid
import ( "bytes" "fmt" "os" "path/filepath" "strconv" "strings" "sync" "syscall" "unsafe")
const ( DefaultVID = 0x2e8a DefaultPID = 0x10fd
EndpointBulkOut = 0x01 EndpointBulkIn = 0x81
DefaultTimeoutMs = 30000
ioctlClaimInterface = 0x8004550f ioctlReleaseInterface = 0x80045510 ioctlBulk = 0xc0185502)
type bulkTransfer struct { ep uint32 len uint32 timeout uint32 data uintptr}
// Device represents a CCID smartcard device connected over Linux USBFS.type Device struct { file *os.File iface uint32 mu sync.Mutex seq byte closed bool atr []byte}
// FindDefaultDevice searches sysfs for the first attached Pico HSM matching DefaultVID:DefaultPID.func FindDefaultDevice() (string, error) { return FindDevice(DefaultVID, DefaultPID)}
// FindDevice searches sysfs for a USB device with the given vendor and product ID.func FindDevice(vid, pid uint16) (string, error) { matches, err := filepath.Glob("/sys/bus/usb/devices/*") if err != nil { return "", err }
vidHex := fmt.Sprintf("%04x", vid) pidHex := fmt.Sprintf("%04x", pid)
for _, devPath := range matches { vBytes, err := os.ReadFile(filepath.Join(devPath, "idVendor")) if err != nil { continue } pBytes, err := os.ReadFile(filepath.Join(devPath, "idProduct")) if err != nil { continue }
if strings.TrimSpace(string(vBytes)) == vidHex && strings.TrimSpace(string(pBytes)) == pidHex { bBytes, err := os.ReadFile(filepath.Join(devPath, "busnum")) if err != nil { continue } dBytes, err := os.ReadFile(filepath.Join(devPath, "devnum")) if err != nil { continue }
busNum, err := strconv.Atoi(strings.TrimSpace(string(bBytes))) if err != nil { continue } devNum, err := strconv.Atoi(strings.TrimSpace(string(dBytes))) if err != nil { continue }
devNode := fmt.Sprintf("/dev/bus/usb/%03d/%03d", busNum, devNum) if _, err := os.Stat(devNode); err == nil { return devNode, nil } } }
return "", fmt.Errorf("device with VID:PID %04X:%04X not found", vid, pid)}
// Open opens the USB device node, claims interface 0, and powers on the ICC slot.func Open(devicePath string) (*Device, error) { f, err := os.OpenFile(devicePath, os.O_RDWR, 0) if err != nil { return nil, fmt.Errorf("open USB device %s: %w", devicePath, err) }
iface := uint32(0) if err := ioctl(int(f.Fd()), ioctlClaimInterface, uintptr(unsafe.Pointer(&iface))); err != nil { _ = f.Close() return nil, fmt.Errorf("claim USB interface %d: %w", iface, err) }
dev := &Device{ file: f, iface: iface, }
// Drain any stale packets left in the endpoint from interrupted operations drainBuf := make([]byte, 2048) for { n, err := dev.bulkRead(EndpointBulkIn, drainBuf, 50) if err != nil || n == 0 { break } }
atr, err := dev.PowerOn() if err != nil { _ = dev.Close() return nil, fmt.Errorf("power on smart card slot: %w", err) } dev.atr = atr
return dev, nil}
// ATR returns the Answer To Reset received when powering on the card.func (d *Device) ATR() []byte { d.mu.Lock() defer d.mu.Unlock() return bytes.Clone(d.atr)}
// Close releases the claimed USB interface and closes the file descriptor.func (d *Device) Close() error { d.mu.Lock() defer d.mu.Unlock()
if d.closed { return nil } d.closed = true
_ = ioctl(int(d.file.Fd()), ioctlReleaseInterface, uintptr(unsafe.Pointer(&d.iface))) return d.file.Close()}
// PowerOn sends the CCID PC_to_RDR_IccPowerOn command and returns the ATR.func (d *Device) PowerOn() ([]byte, error) { d.mu.Lock() defer d.mu.Unlock()
seq := d.nextSeq() msg := BuildPowerOnMsg(seq)
if err := d.bulkWrite(EndpointBulkOut, msg, DefaultTimeoutMs); err != nil { return nil, fmt.Errorf("send PowerOn: %w", err) }
respBuf := make([]byte, 256) n, err := d.bulkRead(EndpointBulkIn, respBuf, DefaultTimeoutMs) if err != nil { return nil, fmt.Errorf("read PowerOn response: %w", err) }
atr, err := ParseDataBlockMsg(respBuf[:n], seq) if err != nil { return nil, fmt.Errorf("parse PowerOn response: %w", err) }
return atr, nil}
// Transmit sends a Command APDU and returns the Response APDU.// It automatically handles 0x61XX (GET RESPONSE) chaining.func (d *Device) Transmit(cmd Command) (Response, error) { d.mu.Lock() defer d.mu.Unlock()
apduBytes := cmd.Bytes() respBytes, err := d.xfrBlock(apduBytes) if err != nil { return Response{}, err }
resp, err := ParseResponse(respBytes) if err != nil { return Response{}, err }
// Automatic GET RESPONSE handling (SW1 == 0x61) for resp.SW1 == 0x61 { le := int(resp.SW2) if le == 0 { le = 256 } getRespCmd := Command{ CLA: 0x00, INS: 0xC0, P1: 0x00, P2: 0x00, Ne: le, } grRespBytes, err := d.xfrBlock(getRespCmd.Bytes()) if err != nil { return resp, fmt.Errorf("GET RESPONSE failed: %w", err) } nextResp, err := ParseResponse(grRespBytes) if err != nil { return resp, fmt.Errorf("parse GET RESPONSE: %w", err) } // Append received data to previous response data resp.Data = append(resp.Data, nextResp.Data...) resp.SW1 = nextResp.SW1 resp.SW2 = nextResp.SW2 }
return resp, nil}
func (d *Device) xfrBlock(apdu []byte) ([]byte, error) { seq := d.nextSeq() msg := BuildXfrBlockMsg(seq, apdu)
if err := d.bulkWrite(EndpointBulkOut, msg, DefaultTimeoutMs); err != nil { return nil, fmt.Errorf("CCID bulk write: %w", err) }
respBuf := make([]byte, 2048) for { n, err := d.bulkRead(EndpointBulkIn, respBuf, DefaultTimeoutMs) if err != nil { return nil, fmt.Errorf("CCID bulk read: %w", err) }
// CCID bmCommandStatus (bits 7-6 of byte 7): // 0b10 (0x80) means Time Extension requested; card is still processing. if n >= HeaderLength && (respBuf[7]&0xC0) == 0x80 { continue }
data, err := ParseDataBlockMsg(respBuf[:n], seq) if err != nil { return nil, fmt.Errorf("CCID data block: %w", err) }
return data, nil }}
func (d *Device) nextSeq() byte { s := d.seq d.seq++ return s}
func (d *Device) bulkWrite(ep uint32, data []byte, timeoutMs uint32) error { if len(data) == 0 { return nil } bt := bulkTransfer{ ep: ep, len: uint32(len(data)), timeout: timeoutMs, data: uintptr(unsafe.Pointer(&data[0])), } return ioctl(int(d.file.Fd()), ioctlBulk, uintptr(unsafe.Pointer(&bt)))}
func (d *Device) bulkRead(ep uint32, buf []byte, timeoutMs uint32) (int, error) { if len(buf) == 0 { return 0, nil } bt := bulkTransfer{ ep: ep, len: uint32(len(buf)), timeout: timeoutMs, data: uintptr(unsafe.Pointer(&buf[0])), } if err := ioctl(int(d.file.Fd()), ioctlBulk, uintptr(unsafe.Pointer(&bt))); err != nil { return 0, err } return int(bt.len), nil}
func ioctl(fd int, req uintptr, arg uintptr) error { _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), req, arg) if err != 0 { return err } return nil}