pcsc

package module
v0.0.0-...-4678299 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2019 License: BSD-3-Clause Imports: 5 Imported by: 883

README

go-libpcsclite

A golang implementation of the libpcpsclite client. It connects to the pcscd daemon over sockets.

Purpose

The goal is for major open source projects to distribute a single binary that doesn't depend on libpcsclite. It provides an extra function CheckPCSCDaemon that will tell the user if pcscd is running.

Example

func main() {
	client, err := EstablishContext(2)
	if err != nil {
    fmt.Printf("Error establishing context: %v\n", err)
    os.Exit(1)
	}

	_, err = client.ListReaders()
	if err != nil {
    fmt.Printf("Error getting the list of readers: %v\n", err)
    os.Exit(1)
	}

	card, err := client.Connect(client.readerStateDescriptors[0].Name, ShareShared, ProtocolT0|ProtocolT1)
	if err != nil {
    fmt.Printf("Error connecting: %v\n", err)
    os.Exit(1)
	}

	resp, _, err := card.Transmit([]byte{0, 0xa4, 4, 0, 0xA0, 0, 0, 8, 4, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0})

	card.Disconnect(LeaveCard)
}

TODO

  • Finish this README
  • Lock context
  • implement missing functions

License

BSD 3-Clause License

Copyright (c) 2019, Guillaume Ballet All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

  • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

  • Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

  • Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Documentation

Index

Constants

View Source
const (
	AutoAllocate  = -1     /* see SCardFreeMemory() */
	ScopeUser     = 0x0000 /* Scope in user space */
	ScopeTerminal = 0x0001 /* Scope in terminal */
	ScopeSystem   = 0x0002 /* Scope in system */
	ScopeGlobal   = 0x0003 /* Scope is global */

	ProtocolUndefined = 0x0000                    /* protocol not set */
	ProtocolUnSet     = ProtocolUndefined         /* backward compat */
	ProtocolT0        = 0x0001                    /* T=0 active protocol. */
	ProtocolT1        = 0x0002                    /* T=1 active protocol. */
	ProtocolRaw       = 0x0004                    /* Raw active protocol. */
	ProtocolT15       = 0x0008                    /* T=15 protocol. */
	ProtocolAny       = (ProtocolT0 | ProtocolT1) /* IFD determines prot. */

	ShareExclusive = 0x0001 /* Exclusive mode only */
	ShareShared    = 0x0002 /* Shared mode only */
	ShareDirect    = 0x0003 /* Raw mode only */

	LeaveCard   = 0x0000 /* Do nothing on close */
	ResetCard   = 0x0001 /* Reset on close */
	UnpowerCard = 0x0002 /* Power down on close */
	EjectCard   = 0x0003 /* Eject on close */

	SCardUnknown    = 0x0001 /* Unknown state */
	SCardAbsent     = 0x0002 /* Card is absent */
	SCardPresent    = 0x0004 /* Card is present */
	SCardSwallowed  = 0x0008 /* Card not powered */
	SCardPowever    = 0x0010 /* Card is powered */
	SCardNegotiable = 0x0020 /* Ready for PTS */
	SCardSpecific   = 0x0040 /* PTS has been set */
)
View Source
const (
	SCardEstablishContext               /* used by SCardEstablishContext() */
	SCardReleaseContext                 /* used by SCardReleaseContext() */
	SCardListReaders                    /* used by SCardListReaders() */
	SCardConnect                        /* used by SCardConnect() */
	SCardReConnect                      /* used by SCardReconnect() */
	SCardDisConnect                     /* used by SCardDisconnect() */
	SCardBeginTransaction               /* used by SCardBeginTransaction() */
	SCardEndTransaction                 /* used by SCardEndTransaction() */
	SCardTransmit                       /* used by SCardTransmit() */
	SCardControl                        /* used by SCardControl() */
	SCardStatus                         /* used by SCardStatus() */
	SCardGetStatusChange                /* not used */
	SCardCancel                         /* used by SCardCancel() */
	SCardCancelTransaction              /* not used */
	SCardGetAttrib                      /* used by SCardGetAttrib() */
	SCardSetAttrib                      /* used by SCardSetAttrib() */
	CommandVersion                      /* get the client/server protocol version */
	CommandGetReaderState               /* get the readers state */
	CommandWaitReaderStateChange        /* wait for a reader state change */
	CommandStopWaitingReaderStateChange /* stop waiting for a reader state change */
)

List of commands to send to the daemon

View Source
const (
	ProtocolVersionMajor = uint32(4) /* IPC major */
	ProtocolVersionMinor = uint32(3) /* IPC minor */
)

Protocol information

View Source
const (
	ReaderStateNameLength       = 128
	ReaderStateMaxAtrSizeLength = 33
	// NOTE: ATR is 32-byte aligned in the C version, which means it's
	// actually 36 byte long and not 33.
	ReaderStateDescriptorLength = ReaderStateNameLength + ReaderStateMaxAtrSizeLength + 5*4 + 3

	MaxReaderStateDescriptors = 16
)

Constants related to the reader state structure

View Source
const (
	SCardConnectReaderNameOffset        = 4
	SCardConnectShareModeOffset         = SCardConnectReaderNameOffset + ReaderStateNameLength
	SCardConnectPreferredProtocolOffset = SCardConnectShareModeOffset + 4
	SCardConnectReturnValueOffset       = SCardConnectPreferredProtocolOffset + 12
)

Offsets into the Connect request/response packet

View Source
const PCSCDSockName string = "/run/pcscd/pcscd.comm"
View Source
const (
	TransmitRequestLength = 32
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Card

type Card struct {
	// contains filtered or unexported fields
}

Card represents the connection to a card

func (*Card) Disconnect

func (card *Card) Disconnect(disposition uint32) error

Disconnect tells the PCSC daemon that the client is no longer interested in communicating with the card.

func (*Card) Transmit

func (card *Card) Transmit(adpu []byte) ([]byte, *SCardIoRequest, error)

Transmit sends request data to a card and returns the response

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client contains all the information needed to establish and maintain a connection to the deamon/card.

func EstablishContext

func EstablishContext(path string, scope uint32) (*Client, error)

EstablishContext asks the PCSC daemon to create a context handle for further communication with connected cards and readers.

func (*Client) Connect

func (client *Client) Connect(name string, shareMode uint32, preferredProtocol uint32) (*Card, error)

Connect asks the daemon to connect to the card

func (*Client) ListReaders

func (client *Client) ListReaders() ([]string, error)

ListReaders gets the list of readers from the daemon

func (*Client) ReleaseContext

func (client *Client) ReleaseContext() error

ReleaseContext tells the daemon that the client will no longer need the context.

type ErrorCode

type ErrorCode uint32
const (
	SCardSuccess                   ErrorCode = 0x00000000 /* No error was encountered. */
	ErrSCardInternal               ErrorCode = 0x80100001 /* An internal consistency check failed. */
	ErrSCardCancelled              ErrorCode = 0x80100002 /* The action was cancelled by an SCardCancel request. */
	ErrSCardInvalidHandle          ErrorCode = 0x80100003 /* The supplied handle was invalid. */
	ErrSCardInvalidParameter       ErrorCode = 0x80100004 /* One or more of the supplied parameters could not be properly interpreted. */
	ErrSCardInvalidTarget          ErrorCode = 0x80100005 /* Registry startup information is missing or invalid. */
	ErrSCardNoMemory               ErrorCode = 0x80100006 /* Not enough memory available to complete this command. */
	ErrSCardWaitedTooLong          ErrorCode = 0x80100007 /* An internal consistency timer has expired. */
	ErrSCardInsufficientBuffer     ErrorCode = 0x80100008 /* The data buffer to receive returned data is too small for the returned data. */
	ErrScardUnknownReader          ErrorCode = 0x80100009 /* The specified reader name is not recognized. */
	ErrSCardTimeout                ErrorCode = 0x8010000A /* The user-specified timeout value has expired. */
	ErrSCardSharingViolation       ErrorCode = 0x8010000B /* The smart card cannot be accessed because of other connections outstanding. */
	ErrSCardNoSmartCard            ErrorCode = 0x8010000C /* The operation requires a Smart Card, but no Smart Card is currently in the device. */
	ErrSCardUnknownCard            ErrorCode = 0x8010000D /* The specified smart card name is not recognized. */
	ErrSCardCannotDispose          ErrorCode = 0x8010000E /* The system could not dispose of the media in the requested manner. */
	ErrSCardProtoMismatch          ErrorCode = 0x8010000F /* The requested protocols are incompatible with the protocol currently in use with the smart card. */
	ErrSCardNotReady               ErrorCode = 0x80100010 /* The reader or smart card is not ready to accept commands. */
	ErrSCardInvalidValue           ErrorCode = 0x80100011 /* One or more of the supplied parameters values could not be properly interpreted. */
	ErrSCardSystemCancelled        ErrorCode = 0x80100012 /* The action was cancelled by the system, presumably to log off or shut down. */
	ErrSCardCommError              ErrorCode = 0x80100013 /* An internal communications error has been detected. */
	ErrScardUnknownError           ErrorCode = 0x80100014 /* An internal error has been detected, but the source is unknown. */
	ErrSCardInvalidATR             ErrorCode = 0x80100015 /* An ATR obtained from the registry is not a valid ATR string. */
	ErrSCardNotTransacted          ErrorCode = 0x80100016 /* An attempt was made to end a non-existent transaction. */
	ErrSCardReaderUnavailable      ErrorCode = 0x80100017 /* The specified reader is not currently available for use. */
	ErrSCardShutdown               ErrorCode = 0x80100018 /* The operation has been aborted to allow the server application to exit. */
	ErrSCardPCITooSmall            ErrorCode = 0x80100019 /* The PCI Receive buffer was too small. */
	ErrSCardReaderUnsupported      ErrorCode = 0x8010001A /* The reader driver does not meet minimal requirements for support. */
	ErrSCardDuplicateReader        ErrorCode = 0x8010001B /* The reader driver did not produce a unique reader name. */
	ErrSCardCardUnsupported        ErrorCode = 0x8010001C /* The smart card does not meet minimal requirements for support. */
	ErrScardNoService              ErrorCode = 0x8010001D /* The Smart card resource manager is not running. */
	ErrSCardServiceStopped         ErrorCode = 0x8010001E /* The Smart card resource manager has shut down. */
	ErrSCardUnexpected             ErrorCode = 0x8010001F /* An unexpected card error has occurred. */
	ErrSCardUnsupportedFeature     ErrorCode = 0x8010001F /* This smart card does not support the requested feature. */
	ErrSCardICCInstallation        ErrorCode = 0x80100020 /* No primary provider can be found for the smart card. */
	ErrSCardICCCreateOrder         ErrorCode = 0x80100021 /* The requested order of object creation is not supported. */
	ErrSCardDirNotFound            ErrorCode = 0x80100023 /* The identified directory does not exist in the smart card. */
	ErrSCardFileNotFound           ErrorCode = 0x80100024 /* The identified file does not exist in the smart card. */
	ErrSCardNoDir                  ErrorCode = 0x80100025 /* The supplied path does not represent a smart card directory. */
	ErrSCardNoFile                 ErrorCode = 0x80100026 /* The supplied path does not represent a smart card file. */
	ErrScardNoAccess               ErrorCode = 0x80100027 /* Access is denied to this file. */
	ErrSCardWriteTooMany           ErrorCode = 0x80100028 /* The smart card does not have enough memory to store the information. */
	ErrSCardBadSeek                ErrorCode = 0x80100029 /* There was an error trying to set the smart card file object pointer. */
	ErrSCardInvalidCHV             ErrorCode = 0x8010002A /* The supplied PIN is incorrect. */
	ErrSCardUnknownResMNG          ErrorCode = 0x8010002B /* An unrecognized error code was returned from a layered component. */
	ErrSCardNoSuchCertificate      ErrorCode = 0x8010002C /* The requested certificate does not exist. */
	ErrSCardCertificateUnavailable ErrorCode = 0x8010002D /* The requested certificate could not be obtained. */
	ErrSCardNoReadersAvailable     ErrorCode = 0x8010002E /* Cannot find a smart card reader. */
	ErrSCardCommDataLost           ErrorCode = 0x8010002F /* A communications error with the smart card has been detected. Retry the operation. */
	ErrScardNoKeyContainer         ErrorCode = 0x80100030 /* The requested key container does not exist on the smart card. */
	ErrSCardServerTooBusy          ErrorCode = 0x80100031 /* The Smart Card Resource Manager is too busy to complete this operation. */
	ErrSCardUnsupportedCard        ErrorCode = 0x80100065 /* The reader cannot communicate with the card, due to ATR string configuration conflicts. */
	ErrSCardUnresponsiveCard       ErrorCode = 0x80100066 /* The smart card is not responding to a reset. */
	ErrSCardUnpoweredCard          ErrorCode = 0x80100067 /* Power has been removed from the smart card, so that further communication is not possible. */
	ErrSCardResetCard              ErrorCode = 0x80100068 /* The smart card has been reset, so any shared state information is invalid. */
	ErrSCardRemovedCard            ErrorCode = 0x80100069 /* The smart card has been removed, so further communication is not possible. */
	ErrSCardSecurityViolation      ErrorCode = 0x8010006A /* Access was denied because of a security violation. */
	ErrSCardWrongCHV               ErrorCode = 0x8010006B /* The card cannot be accessed because the wrong PIN was presented. */
	ErrSCardCHVBlocked             ErrorCode = 0x8010006C /* The card cannot be accessed because the maximum number of PIN entry attempts has been reached. */
	ErrSCardEOF                    ErrorCode = 0x8010006D /* The end of the smart card file has been reached. */
	ErrSCardCancelledByUser        ErrorCode = 0x8010006E /* The user pressed "Cancel" on a Smart Card Selection Dialog. */
	ErrSCardCardNotAuthenticated   ErrorCode = 0x8010006F /* No PIN was presented to the smart card. */
)

func (ErrorCode) Code

func (code ErrorCode) Code() uint32

Code returns the error code, with an uint32 type to be used in PutUInt32

func (ErrorCode) Error

func (code ErrorCode) Error() error

type ReaderState

type ReaderState struct {
	Name string /* reader name */
	// contains filtered or unexported fields
}

ReaderState represent the state of a single reader, as reported by the PCSC daemon.

type SCardIoRequest

type SCardIoRequest struct {
	// contains filtered or unexported fields
}

SCardIoRequest contains the info needed for performing an IO request

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL