freefare

package
v0.0.0-...-068cc5b Latest Latest
Warning

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

Go to latest
Published: May 5, 2020 License: LGPL-3.0 Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	KeyA = iota
	KeyB
)

Mifare Classic key types

View Source
const (
	AccessBitI = 1 << iota
	AccessBitD
	AccessBitW
	AccessBitR
)

Mifare Classic access bits

View Source
const (
	WriteKeyB = 1 << (2 * iota)
	ReadKeyB
	WriteAccessBits
	ReadAccessBits
	WriteKeyA
	ReadKeyA
)

Other Mifare Classic constants

View Source
const (
	StandardDataFile = iota
	BackupDataFile
	ValueFileWithBackup
	LinearRecordFileWithBackup
	CyclicRecordFileWithBackup
)

DESFire file types as used in DESFireFileSettings

View Source
const (
	Free = 0xe
	Deny = 0xf
)

Mifare DESFire access rights. This wrapper does not provide the constants MDAR_KEY0 ... MDAR_KEY13 as they are just 0 ... 13.

View Source
const (
	CryptoDES    = 0x00
	Crypto3k3DES = 0x40
	CryptoAES    = 0x80
)

DESFire cryptography modes. Compute the bitwise or of these constants and the key number to select a certain cryptography mode.

View Source
const (
	Plain      = 0x00
	Maced      = 0x01
	Enciphered = 0x03

	// let the wrapper deduct the communication mode
	Default = 0xff
)

Mifare DESFire communication modes

View Source
const (
	OperationOK         = 0x00
	CryptoError         = 0x01
	NoChanges           = 0x0C
	OutOfEEPromError    = 0x0E
	IllegalCommandCode  = 0x1C
	IntegrityError      = 0x1E
	NoSuchKey           = 0x40
	LengthError         = 0x7E
	PermissionError     = 0x9D
	ParameterError      = 0x9E
	ApplicationNotFound = 0xA0
	ApplIntegrityError  = 0xA1
	AuthenticationError = 0xAE
	AdditionalFrame     = 0xAF
	BoundaryError       = 0xBE
	PICCIntegrityError  = 0xC1
	CommandAborted      = 0xCA
	PICCDisabledError   = 0xCD
	CountError          = 0xCE
	DuplicateError      = 0xDE
	EEPromError         = 0xEE
	FileNotFound        = 0xF0
	FileIntegrityError  = 0xF1
)

PICC and PCD status and error codes. This wrapper will return nil on success, expect to not see OPERATION_OK anywhere.

View Source
const (
	// libfreefare versions up to 0.4.0 do not set errno on authentication
	// failure. Instead you will see this unknown error which may or may not
	// indicate an authentication failure. AUTHENTICATION_ERROR is returned
	// on newer versions.
	UnknownError = 0x100 + iota

	// The tag was inactive when it was expected to be active or vice versa
	TagStateError
	InvalidTagType
	MadVersionNotSup // MAD version not supported
)

Status and error codes used by this wrapper in addition to the PICC / PCD codes. These are mostly errno values represented in a more useful way.

View Source
const (
	Ultralight = iota
	UltralightC
	Classic1k
	Classic4k
	DESFire
)

Mifare tag types

Variables

View Source
var (
	// AID - Administration codes
	FreeAid          = NewMadAid(0x00, 0x00)
	DefectAid        = NewMadAid(0x01, 0x00)
	ReservedAid      = NewMadAid(0x02, 0x00)
	CardHolderAid    = NewMadAid(0x04, 0x00)
	NotApplicableAid = NewMadAid(0x05, 0x00)

	// NFC Forum AID
	MadNFCForumAid = NewMadAid(0x03, 0xe1)
)

Predefined MadAid values

Functions

func ClassicBlockSector

func ClassicBlockSector(block byte) (sector byte)

Compute a Mifare Classic sector number from a block number

func ClassicSectorBlockCount

func ClassicSectorBlockCount(sector byte) int

Compute the number of blocks in a Mifare Classic sector

func ClassicSectorFirstBlock

func ClassicSectorFirstBlock(sector byte) (block byte)

Compute a Mifare Classic sector's first block number

func ClassicSectorLastBlock

func ClassicSectorLastBlock(sector byte) (block byte)

Get a Mifare Classic sector's last block number (i.e. trailer block)

func MakeDESFireAccessRights

func MakeDESFireAccessRights(read, write, readWrite, changeAccessRights byte) uint16

Create an uint16 out of individual access rights. This function only looks at the low nibbles of each parameter. This function implements the functionality of the MDAR macro from the freefare.h header.

func SplitDESFireAccessRights

func SplitDESFireAccessRights(ar uint16) (read, write, readWrite, changeAccessRights byte)

Split an access rights block into individual access rights. This function implements the functionality of the MDAR_### family of macros.

func TLVdecode

func TLVdecode(istream []byte) (ostream []byte, t byte)

Decode TLV from data stream. This function implements the functionality of tlv_decode().

func TLVencode

func TLVencode(istream []byte, t byte) []byte

Encode data stream into TLV. This function expects that len(istream) < 65536. Iff this doesn't hold, this function returns nil. This function implements the functionality of tlv_encode().

func TLVrecordLength

func TLVrecordLength(istream []byte) (fls, fvs int)

Get field length size (fls) and field value size (fvs) of a TLV record. This function implements the functionality of tlv_record_length().

Types

type ClassicTag

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

Convert a Tag into a ClassicTag to access functionality available for Mifare Classic tags.

func (ClassicTag) Authenticate

func (t ClassicTag) Authenticate(block byte, key [6]byte, keyType int) error

Authenticate against a Mifare Classic tag. Use the provided constants for keyType.

func (ClassicTag) Connect

func (t ClassicTag) Connect() error

Connect to a Mifare Classic tag. This causes the tag to be active.

func (ClassicTag) DataBlockPermission

func (t ClassicTag) DataBlockPermission(block, permission byte, keyType int) (bool, error)

Get information about data blocks

func (ClassicTag) Decrement

func (t ClassicTag) Decrement(block byte, amount uint32) error

Decrement the given value block by the provided amount

func (ClassicTag) Device

func (t ClassicTag) Device() nfc.Device

Get the nfc.Devcice that was used to create t

func (ClassicTag) Disconnect

func (t ClassicTag) Disconnect() error

Disconnect from a Mifare Classic tag. This causes the tag to be inactive.

func (ClassicTag) FormatSector

func (t ClassicTag) FormatSector(sector byte) error

Reset a Mifare Classic target sector to factory default

func (ClassicTag) Increment

func (t ClassicTag) Increment(block byte, amount uint32) error

Increment the given value block by the provided amount

func (ClassicTag) Pointer

func (t ClassicTag) Pointer() uintptr

Get a pointer to the wrapped MifareTag structure. Be careful with this pointer: This wrapper deallocates the MifareTag once the associated Tag object becomes unreachable. Always keep a reference to the Tag structure when doing fancy stuff with the pointer!

For security reasons, this function returns an uintptr. Use the package unsafe to do something with it.

func (ClassicTag) ReadApplication

func (t ClassicTag) ReadApplication(m *Mad, aid MadAid, buf []byte, key [6]byte, keyType int) (int, error)

Read the provided application sectors from a Mifare Classic tag. This function returns the number of sectors read or a negative number and an error. This function wraps mifare_application_read().

func (ClassicTag) ReadBlock

func (t ClassicTag) ReadBlock(block byte) ([16]byte, error)

Read a block of data from a Mifare Classic tag. Notice that this function has been renamed to avoid confusion with the Read() function from io.Reader.

func (ClassicTag) ReadMad

func (t ClassicTag) ReadMad() (*Mad, error)

Read a MAD from a Mifare Classic tag. This function wraps mad_read().

func (ClassicTag) Restore

func (t ClassicTag) Restore(block byte) error

Restore the content of a block

func (ClassicTag) String

func (t ClassicTag) String() string

Get the friendly name of a Tag. This function wraps freefare_get_tag_friendly_name().

func (ClassicTag) TrailerBlockPermission

func (t ClassicTag) TrailerBlockPermission(block byte, permission uint16, keyType int) (bool, error)

Get information about the trailer block. Use the provided constants for keyType. This function doesn't work for block 0.

func (ClassicTag) Transfer

func (t ClassicTag) Transfer(block byte) error

Transfer the internal data register to the provided block

func (ClassicTag) TranslateError

func (t ClassicTag) TranslateError(e error) error

Translate errno value into Go error. This function can be used in modules that wrap C code that use the libfreefare. Use a two-return call to get the value of errno and pass errno to TranslateError() if an error occured like this:

ret, errno := C.do_something_with_a_tag(tag.Pointer())
if error_occured {
    err := tag.TranslateError(errno)
    /* normal error handling with err */
}

If e is not a nil pointer and not of type syscall.Errno, this function panics.

func (ClassicTag) Type

func (t ClassicTag) Type() int

Get the type of a Tag. The returned integer can be compared against the supplied constants to figure out what kind of tag it is.

func (ClassicTag) UID

func (t ClassicTag) UID() string

Get the UID of a Tag. The UID is a string of hexadecimal digits.

func (ClassicTag) WriteApplication

func (t ClassicTag) WriteApplication(m *Mad, aid MadAid, buf []byte, key [6]byte, keyType int) (int, error)

Write the provided application sector to a Mifare Classic tag. This function returns the number of bytes written or a negative number and an error. This function wraps mifare_application_write().

func (ClassicTag) WriteBlock

func (t ClassicTag) WriteBlock(block byte, data [16]byte) error

Write a block of data to a Mifare Classic tag. Notice that this function has been renamed to avoid confusion with the Write() function from io.Writer.

func (ClassicTag) WriteMad

func (t ClassicTag) WriteMad(m *Mad, sector00keyB, sector10keyB [6]byte) error

Write a MAD to a Mifare tag using the provided Key-B keys.

type DESFireAid

type DESFireAid [3]byte

A Mifare DESFire application ID. For performance reasons, the DESFireAid functionality has been reimplemented in Go instead of wrapping C code. You can safely do something like this when interfacing with C code:

aid := NewDESFireAid(0x1234)
caid := C.MifareDESFireAid(unsafe.Pointer(aid))

func NewDESFireAid

func NewDESFireAid(aid uint32) (m DESFireAid)

Create a new Mifare DESFire Aid. This function ignores the high eight bits of aid.

func NewDESFireAidWithMadAid

func NewDESFireAidWithMadAid(ma MadAid, n byte) DESFireAid

Create a new Mifare DESFire Aid using a Mifare Classic Aid and n as the last nibble of the new Aid. This function ease the MifareDESFireAid creation using a Mifare Classic Aid (see MIFARE Application Directory document - section 3.10 MAD and MIFARE DESFire). This function ignores the most-significant four bits of n.

func (DESFireAid) Aid

func (aid DESFireAid) Aid() uint32

Return an integer representationn

type DESFireDF

type DESFireDF struct {
	DESFireAid
	Fid  uint16 // file ID
	Name []byte // no longer than 16 bytes
}

A Mifare DESFire directory file

type DESFireFileSettings

type DESFireFileSettings struct {
	FileType              byte
	CommunicationSettings byte
	AccessRights          uint16

	// FileType == STANDARD_DATA_FILE || FileType == BACKUP_DATA_FILE
	FileSize uint32

	// FileType == VALUE_FILE_WITH_BACKUP
	LowerLimit, UpperLimit int32
	LimitedCreditValue     int32
	LimitedCreditEnabled   byte

	// FileType == LINEAR_RECORD_FILE_WITH_BACKUP || CYCLIC_RECORD_FILE_WITH_BACKUP
	RecordSize             uint32
	MaxNumberOfRecords     uint32
	CurrentNumberOfRecords uint32
}

This type remodels struct mifare_desfire_file_settings. Because Go does not support union types, this struct contains all union members laid out sequentially. Only the set of members denoted by FileType is valid. Use the supplied constants for FileType.

Use the function SplitDESFireAccessRights() to split the AccessRights field.

type DESFireKey

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

This structure wraps a MifareDESFireKey.

func NewDESFire3DESKey

func NewDESFire3DESKey(value [16]byte) *DESFireKey

Create a new 3DES key. This function wraps the verbosely named function mifare_desfire_3des_key_new_with_version. To get a result equal to what mifare_desfire_3des_key_new does, set the version to 0 after creating the key or clear the lowest bits of the first eight bytes and set the lowest bits of the last eight using code like this:

var value [16]byte
/* ... */

for i := 0; i < 8; i++ {
    value[i] ^&= 1
}

for i := 8; i < 16; i++ {
    value[i] |= 1
}

key := NewDESFireDES3Key(value)

func NewDESFire3K3DESKey

func NewDESFire3K3DESKey(value [24]byte) *DESFireKey

Create a new 3K3DES key. This function wraps the verbosely named function mifare_desfire_3k3des_key_new_with_version. To get a result equal to what mifare_desfire_3k3des_key_new does, set the version to 0 after creating the key or clear the lowest bit of each byte using code like this:

var value [24]byte
/* ... */

for i := 0; i < 8; i++ {
    value[i] ^&= 1
}

key := NewDESFire3K3DESKey(value)

func NewDESFireAESKey

func NewDESFireAESKey(value [16]byte, version byte) *DESFireKey

Create a new AES key. This function wraps the verbosely named function mifare_desfire_aes_key_new_with_version. To get a result equal to what mifare_desfire_aes_key_new does, pass 0 as version.

func NewDESFireDESKey

func NewDESFireDESKey(value [8]byte) *DESFireKey

Create a new DES key. This function wraps the verbosely named function mifare_desfire_des_key_new_with_version. To get a result equal to what mifare_desfire_des_key_new does, set the version to 0 after creating the key or clear the lowest bit of each byte using code like this:

var value [8]byte
/* ... */

for i := range value {
    value[i] ^&= 1
}

key := NewDESFireDESKey(value)

func (*DESFireKey) Pointer

func (k *DESFireKey) Pointer() uintptr

Get a pointer to the wrapped MifareDESFireKey structure. Be careful with this pointer: This wrapper deallocates the MifareDESFireKey once the associated DESFireKey object becomes unreachable. Always keep a reference to the DESFireKey structure when doing fancy stuff with the pointer!

For security reasons, this function returns an uintptr. Use the package unsafe to do something with it.

func (*DESFireKey) SetVersion

func (k *DESFireKey) SetVersion(version byte)

Set the version of a Mifare DESFireKey.

func (*DESFireKey) Version

func (k *DESFireKey) Version() byte

Get the version of a Mifare DESFireKey.

type DESFireTag

type DESFireTag struct {

	// communication settings
	WriteSettings, ReadSettings byte
	// contains filtered or unexported fields
}

Convert a Tag into an DESFireTag to access functionality available for Mifare DESFire tags. As opposed to the libfreefare itself, this wrapper does not provide data-level operations with explicit communication settings. Instead, the wrapper uses the settings stored in the DESFireTag struct or automatically detects them (as if the libfreefare non-ex function was called) if they are set to DEFAULT. When this wrapper creates a new DESFireTag, WriteSettings and ReadSettings are set to DEFAULT so each data access operation behaves like the underlying libfreefare function.

func (DESFireTag) AbortTransaction

func (t DESFireTag) AbortTransaction() error

Roll back pending changes to the tag.

func (DESFireTag) ApplicationIds

func (t DESFireTag) ApplicationIds() ([]DESFireAid, error)

Return a list of all applications of the card

func (DESFireTag) Authenticate

func (t DESFireTag) Authenticate(keyNo byte, key DESFireKey) error

Authenticate to a Mifare DESFire tag. Notice that this wrapper does not provide wrappers for the mifare_desfire_authenticate_iso() and mifare_desfire_authenticate_aes() functions as the key type can be deducted from the key.

func (DESFireTag) CardUID

func (t DESFireTag) CardUID() (string, error)

Get the card's UID. This function can be used to get the original UID of the target if the PICC is configured to return a random UID. The return value of CardUID() has the same format as the return value of UID(), but this function may fail.

func (DESFireTag) ChangeFileSettings

func (t DESFireTag) ChangeFileSettings(fileNo, communicationSettings byte, accessRights uint16) error

Change the communication settings and access rights of file fileNo of the selected application of t. Use the function MakeDESFireAccessRights() to create a suitable accessRights parameter.

func (DESFireTag) ChangeKey

func (t DESFireTag) ChangeKey(keyNo byte, newKey, oldKey DESFireKey) error

Change the key keyNo from oldKey to newKey. Depending on the application settings, a previous authentication with the same key or another key may be required.

func (DESFireTag) ChangeKeySettings

func (t DESFireTag) ChangeKeySettings(s byte) error

Change the selected application settings to s. The application number of keys cannot be changed after the application has been created.

func (DESFireTag) ClearRecordFile

func (t DESFireTag) ClearRecordFile(fileNo byte) error

Erase all records from the record file fileNo

func (DESFireTag) CommitTransaction

func (t DESFireTag) CommitTransaction() error

Validate pending changes to the tag.

func (DESFireTag) Connect

func (t DESFireTag) Connect() error

Connect to a Mifare DESFire tag. This causes the tag to be active.

func (DESFireTag) CreateApplication

func (t DESFireTag) CreateApplication(aid DESFireAid, settings, keyNo byte) error

Create a new application with AID aid, settings and keyNo authentication keys. Authentication keys are set to 0 after creation. This wrapper does not wrap the functions mifare_desfire_create_application_3k3des() and mifare_desfire_create_application_aes(). Or keyNo with the constants CRYPTO_3K3DES and CRYPTO_AES instead.

func (DESFireTag) CreateApplicationIso

func (t DESFireTag) CreateApplicationIso(
	aid DESFireAid,
	settings byte,
	keyNo byte,
	wantIsoFileIdentifiers bool,
	isoFileID uint16,
	isoFileName []byte,
) error

Create a new application with AID aid, settings, keyNo authentication keys, and, if wantIsoFileIdentifiers is true, an ISO file ID and an optional file name isoFileName. This wrapper does not wrap the functions mifare_desfire_create_application_3k3des_iso and mifare_desfire_create_application_aes_iso(). Or keyNo with the constants CRYPTO_3K3DES and CRYPTO_AES instead.

func (DESFireTag) CreateDataFile

func (t DESFireTag) CreateDataFile(
	fileNo byte,
	communicationSettings byte,
	accessRights uint16,
	fileSize uint32,
	isBackup bool,
) error

Create a standard or backup data file of size fileSize. This function wraps either mifare_desfire_create_std_data_file() or mifare_desfire_create_backup_data_file() depending on the value of isBackup.

func (DESFireTag) CreateDataFileIso

func (t DESFireTag) CreateDataFileIso(
	fileNo byte,
	communicationSettings byte,
	accessRights uint16,
	fileSize uint32,
	isoFileId uint16,
	isBackup bool,
) error

Create a standard or backup data file of size fileSize with an ISO file ID. This function wraps either mifare_desfire_create_std_data_file_iso() or mifare_desfire_create_backup_data_file_iso() depending on the value of isBackup.

func (DESFireTag) CreateRecordFile

func (t DESFireTag) CreateRecordFile(
	fileNo byte,
	communicationSettings byte,
	accessRights uint16,
	recordSize uint32,
	maxNumberOfRecords uint32,
	isCyclic bool,
) error

Create linear or cyclic record file that can holf maxNumberOfRecords of size recordSize. This function wraps either mifare_desfire_create_linear_record_file() or mifare_desfire_create_cyclic_record_file() depending on the value of the isCyclic parameter.

func (DESFireTag) CreateRecordFileIso

func (t DESFireTag) CreateRecordFileIso(
	fileNo byte,
	communicationSettings byte,
	accessRights uint16,
	recordSize uint32,
	maxNumberOfRecords uint32,
	isoFileId uint16,
	isCyclic bool,
) error

Create linear or cyclic record file that can holf maxNumberOfRecords of size recordSize with an ISO file ID. This function wraps either mifare_desfire_create_linear_record_file_iso() or mifare_desfire_create_cyclic_record_file_iso() depending on the value of the isCyclic parameter.

func (DESFireTag) CreateValueFile

func (t DESFireTag) CreateValueFile(
	fileNo byte,
	communicationSettings byte,
	accessRights uint16,
	lowerLimit, upperLimit, value int32,
	limitedCreditEnable byte,
) error

Create a value file of value value constrained in the range lowerLimit to upperLimit and with the limitedCreditEnable settings.

func (DESFireTag) Credit

func (t DESFireTag) Credit(fileNo byte, amount int32) error

Add amount to the value of the file fileNo.

This function wraps either mifare_desfire_credit() or mifare_desfire_credit_ex(), depending on the value of t.WriteSettings.

func (DESFireTag) DFNames

func (t DESFireTag) DFNames() ([]DESFireDF, error)

Retrieve a list of directory file (df) names

func (DESFireTag) Debit

func (t DESFireTag) Debit(fileNo byte, amount int32) error

Subtract amount from the value of the file fileNo.

This function wraps either mifare_desfire_debit() or mifare_desfire_debit_ex(), depending on the value of t.WriteSettings.

func (DESFireTag) DeleteApplication

func (t DESFireTag) DeleteApplication(aid DESFireAid) error

Delete the application identified by aid

func (DESFireTag) DeleteFile

func (t DESFireTag) DeleteFile(fileNo byte) error

Remove the file fileNo from the selected application

func (DESFireTag) Device

func (t DESFireTag) Device() nfc.Device

Get the nfc.Devcice that was used to create t

func (DESFireTag) Disconnect

func (t DESFireTag) Disconnect() error

Disconnect from a Mifare DESFire tag. This causes the tag to be inactive.

func (DESFireTag) FileIds

func (t DESFireTag) FileIds() ([]byte, error)

Return a list of files in the selected application

func (DESFireTag) FileSettings

func (t DESFireTag) FileSettings(fileNo byte) (DESFireFileSettings, error)

Retrieve the settings of the file fileNo of the selected application of t.

func (DESFireTag) FormatPICC

func (t DESFireTag) FormatPICC() error

Reset t to factory defaults. For this function to work, a previous authentication with the card master key is required. WARNING: This function is irreversible and will delete all date on the card.

func (DESFireTag) FreeMem

func (t DESFireTag) FreeMem() (uint32, error)

Get the amount of free memory on the PICC of a Mifare DESFire tag in bytes.

func (DESFireTag) IsoFileIds

func (t DESFireTag) IsoFileIds() ([]uint16, error)

Return a list of ISO file identifiers

func (DESFireTag) KeySettings

func (t DESFireTag) KeySettings() (settings, maxKeys byte, err error)

Return the key settings and maximum number of keys for the selected application.

func (DESFireTag) KeyVersion

func (t DESFireTag) KeyVersion(keyNo byte) (byte, error)

Retrieve the version of the key keyNo for the selected application.

func (DESFireTag) LastPCDError

func (t DESFireTag) LastPCDError() error

Get last PCD error. This function wraps mifare_desfire_last_pcd_error(). If no error has occured, this function returns nil.

func (DESFireTag) LastPICCError

func (t DESFireTag) LastPICCError() error

Get last PICC error. This function wraps mifare_desfire_last_picc_error(). If no error has occured, this function returns nil.

func (DESFireTag) LimitedCredit

func (t DESFireTag) LimitedCredit(fileNo byte, amount int32) error

Add amount to the value of the file fileNo.

This function wraps either mifare_desfire_credit() or mifare_desfire_credit_ex(), depending on the value of t.WriteSettings.

func (DESFireTag) Pointer

func (t DESFireTag) Pointer() uintptr

Get a pointer to the wrapped MifareTag structure. Be careful with this pointer: This wrapper deallocates the MifareTag once the associated Tag object becomes unreachable. Always keep a reference to the Tag structure when doing fancy stuff with the pointer!

For security reasons, this function returns an uintptr. Use the package unsafe to do something with it.

func (DESFireTag) ReadData

func (t DESFireTag) ReadData(fileNo byte, offset int64, buf []byte) (int, error)

Read bytes from data file fileNo at offset offset. This function returns the number of bytes read or an error. As opposed to the underlying function mifare_desfire_read_data(), there is no mechanism to read all data from the file, this function is a nop if len(buf) == 0. Try passing a large enough buffer instead.

This function wraps either mifare_desfire_read_data() or mifare_desfire_read_data_ex(), depending on the value of t.ReadSettings.

func (DESFireTag) ReadRecords

func (t DESFireTag) ReadRecords(fileNo byte, offset int64, buf []byte) (int, error)

Read len(data) records starting at record offset from the record file fileNo and copy them to data, returning the number of bytes read or an error.

This function wraps either mifare_desfire_read_records() or mifare_desfire_read_records_ex(), depending on the value of t.ReadSettings.

func (DESFireTag) SelectApplication

func (t DESFireTag) SelectApplication(aid DESFireAid) error

Select an application. After Connect(), the master application is selected. This function can be used to select a different application.

func (DESFireTag) SetAts

func (t DESFireTag) SetAts(ats []byte) error

Replace the ATS bytes returned by the PICC when it is selected. This function performs the following extra test in order to ensure memory safety:

if len(ats) < int(ats[0]) {
    return Error(PARAMETER_ERROR)
}

func (DESFireTag) SetConfiguration

func (t DESFireTag) SetConfiguration(disableFormat, enableRandomUID bool) error

This function can be used to deactivate the format function or to switch to use a random UID.

func (DESFireTag) String

func (t DESFireTag) String() string

Get the friendly name of a Tag. This function wraps freefare_get_tag_friendly_name().

func (DESFireTag) TranslateError

func (t DESFireTag) TranslateError(e error) error

Translate errno value into Go error. This function can be used in modules that wrap C code that use the libfreefare. Use a two-return call to get the value of errno and pass errno to TranslateError() if an error occured like this:

ret, errno := C.do_something_with_a_tag(tag.Pointer())
if error_occured {
    err := tag.TranslateError(errno)
    /* normal error handling with err */
}

If e is not a nil pointer and not of type syscall.Errno, this function panics.

func (DESFireTag) Type

func (t DESFireTag) Type() int

Get the type of a Tag. The returned integer can be compared against the supplied constants to figure out what kind of tag it is.

func (DESFireTag) UID

func (t DESFireTag) UID() string

Get the UID of a Tag. The UID is a string of hexadecimal digits.

func (DESFireTag) Value

func (t DESFireTag) Value(fileNo byte) (int32, error)

Read the value of value file fileNo.

This function wraps either mifare_desfire_get_value() or mifare_desfire_get_value_ex(), depending on the value of t.ReadSettings.

func (DESFireTag) Version

func (t DESFireTag) Version() (DESFireVersionInfo, error)

Retrieve various information about t including UID. batch number, production date, hardware and software information.

func (DESFireTag) WriteData

func (t DESFireTag) WriteData(fileNo byte, offset int64, buf []byte) (int, error)

Write bytes to data file fileNo at offset offset. This function returns the number of bytes written or an error.

This function wraps either mifare_desfire_write_data() or mifare_desfire_write_data_ex(), depending on the value of t.WriteSettings.

func (DESFireTag) WriteRecord

func (t DESFireTag) WriteRecord(fileNo byte, offset int64, buf []byte) (int, error)

Write len(data) records starting at record from data to the record file fileNo and return the number of bytes written or an error.

This function wraps either mifare_desfire_write_record() or mifare_desfire_write_record_ex(), depending on the value of t.WriteSettings.

type DESFireVersionInfo

type DESFireVersionInfo struct {
	Hardware, Software struct {
		VendorID                   byte
		Type, Subtype              byte
		VersionMajor, VersionMinor byte
		StorageSize                byte
		Protocol                   byte
	}

	UID                            [7]byte
	BatchNumber                    [5]byte
	ProductionWeek, ProductionYear byte
}

Version information for a Mifare DESFire tag.

type Error

type Error int

A MIFARE error. Functions in this library that return an error return either an object of this type or an object of type nfc.Error if failure occured in the libnfc. Values of type Error can be matched against the various symbolic constants provided. All values in the range 0x00 to 0xff are unchanged PICC or PCD error codes from the libfreefare. Error codes with values higher than 0xff are custom additions by this Go wrapper to denote errors communicated over errno values.

func (Error) Error

func (e Error) Error() string

Get the error string of an Error

type Mad

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

A Mifare application directory. This struct wraps Mad. The wrapper takes care of automatic deallocation.

func NewMad

func NewMad(version byte) *Mad

Create a new MAD. The Go wrapper automatically takes care of allocation and deallocation.

func (*Mad) Aid

func (m *Mad) Aid(sector byte) (MadAid, error)

Get the provided sector's application identifier. An error occurs if sector is invalid.

func (*Mad) AllocApplication

func (m *Mad) AllocApplication(aid MadAid, size uint) []byte

Allocate a new application into a MAD. This function returns a slice of newly allocated sectors. This function returns nil if the application already exists. This function wraps mifare_application_alloc().

func (*Mad) FindApplication

func (m *Mad) FindApplication(aid MadAid) []byte

Get all sector numbers of an application from the provided MAD. This function returns nil if the application could not be found. This function mifare_application_find().

func (*Mad) FreeApplication

func (m *Mad) FreeApplication(aid MadAid)

Remove an application from a MAD. If the application does not exist, this function is a NOP. This function wraps mifare_application_free().

func (*Mad) PublisherSector

func (m *Mad) PublisherSector() byte

Get the number of the publisher sector

func (*Mad) Reserved

func (m *Mad) Reserved(sector byte) bool

Tell if a certain sector has been reserved. This wraps mad_sector_reserved().

func (*Mad) SetAid

func (m *Mad) SetAid(sector byte, aid MadAid) error

Set the provided sector's application identifier. An error occurs if the sector is invalid.

func (*Mad) SetPublisherSector

func (m *Mad) SetPublisherSector(cps byte) error

Set the MAD card publisher sector number. This returns an error if the sector number you provided is invalid.

func (*Mad) SetVersion

func (m *Mad) SetVersion(version byte)

Set MAD version. This function wraps mad_set_version().

func (*Mad) Version

func (m *Mad) Version() int

Get MAD version. This function wraps mad_get_version().

type MadAid

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

Wraps a MadAid (MAD application identifier). Use the provided accessor functions to operate on objects of this type.

func NewMadAid

func NewMadAid(applicationCode, functionClusterCode byte) MadAid

Make a new MadAid

func (MadAid) ApplicationCode

func (m MadAid) ApplicationCode() byte

Read the application_code field

func (MadAid) Content

func (m MadAid) Content() (applicationCode, functionClusterCode byte)

Read all parameters from a MadAid

func (MadAid) FunctionClusterCode

func (m MadAid) FunctionClusterCode() byte

Read the function_cluster_code field

type Tag

type Tag interface {
	Connect() error
	Device() nfc.Device
	Disconnect() error
	Pointer() uintptr
	String() string
	TranslateError(error) error
	Type() int
	UID() string
}

This interface represents a Mifare tag of arbitrary type. You can figure out its type using the Type() method. To access features of a specific type of tag, cast it to the appropriate tag type.

This interface is not designed to have other packages implement it. If you do so, strange things may happen.

func GetTags

func GetTags(d nfc.Device) ([]Tag, error)

Get a list of the MIFARE targets near to the provided NFC initiator. If the list of tags cannot be generated, an error is returned. The Go wrapper takes care of allocating and deallocating Tags. No precautions are needed.

func NewTag

func NewTag(d nfc.Device, info *nfc.ISO14443aTarget) (Tag, error)

Automagically allocate a Tag given a device and target info. The Go wrapper takes care of allocating and deallocating Tags. No precautions are needed. The Baud field of the info parameter is not evaluated.

type UltralightTag

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

Convert a Tag into an UltralightTag to access functionality available for Mifare Ultralight tags.

func (UltralightTag) Authenticate

func (t UltralightTag) Authenticate(key DESFireKey) error

Authentificate to a Mifare Ultralight tag. Note that this only works with MifareUltralightC tags.

func (UltralightTag) Connect

func (t UltralightTag) Connect() error

Connect to a Mifare Ultralight tag. This causes the tag to be active.

func (UltralightTag) Device

func (t UltralightTag) Device() nfc.Device

Get the nfc.Devcice that was used to create t

func (UltralightTag) Disconnect

func (t UltralightTag) Disconnect() error

Disconnect from a Mifare Ultralight tag. This causes the tag to be inactive.

func (UltralightTag) Pointer

func (t UltralightTag) Pointer() uintptr

Get a pointer to the wrapped MifareTag structure. Be careful with this pointer: This wrapper deallocates the MifareTag once the associated Tag object becomes unreachable. Always keep a reference to the Tag structure when doing fancy stuff with the pointer!

For security reasons, this function returns an uintptr. Use the package unsafe to do something with it.

func (UltralightTag) ReadPage

func (t UltralightTag) ReadPage(page byte) ([4]byte, error)

Read one page of data from a Mifare Ultralight tag. page denotes the page number you want to read. Notice that page should not be larger than 16 in case of an Ultralight tag and not larger than 44 in case of an Ultralight C tag.

Please notice that this function has been renamed to avoid confusion with the Read() function from io.Reader.

func (UltralightTag) String

func (t UltralightTag) String() string

Get the friendly name of a Tag. This function wraps freefare_get_tag_friendly_name().

func (UltralightTag) TranslateError

func (t UltralightTag) TranslateError(e error) error

Translate errno value into Go error. This function can be used in modules that wrap C code that use the libfreefare. Use a two-return call to get the value of errno and pass errno to TranslateError() if an error occured like this:

ret, errno := C.do_something_with_a_tag(tag.Pointer())
if error_occured {
    err := tag.TranslateError(errno)
    /* normal error handling with err */
}

If e is not a nil pointer and not of type syscall.Errno, this function panics.

func (UltralightTag) Type

func (t UltralightTag) Type() int

Get the type of a Tag. The returned integer can be compared against the supplied constants to figure out what kind of tag it is.

func (UltralightTag) UID

func (t UltralightTag) UID() string

Get the UID of a Tag. The UID is a string of hexadecimal digits.

func (UltralightTag) WritePage

func (t UltralightTag) WritePage(page byte, data [4]byte) error

Write one page of data from a Mifare Ultralight tag. page denotes the page number you want to write. Notice that page should not be larger than 16 in case of an Ultralight tag and not larger than 48 in case of an Ultralight C tag.

Please notice that this function has been renamed to avoid confusion with the Write() function from io.Writer.

Notes

Bugs

  • The libfreefare <= 0.4.0 may use more bytes of buf than available; memory corruption may happen. I have yet to figure out how to mitigate this issue.

  • The libfreefare <= 0.4.0 may use more bytes of buf than available; memory corruption may happen. I have yet to figure out how to mitigate this issue.

Jump to

Keyboard shortcuts

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