Sending APDU with winscard.dll (PC/SC) without a smart card connected - apdu

I'm trying to send APDU commands to the card reader itself instead of the Smart Card. The test command I'm using turns the RF field on and off.
This commands sends over SCardTransmit if I first connected to a smart card. But as soon as the RF field is off, the card disconnects and I cant send another APDU to turn the field on.
Basically is there any way to send APDU's over pc/sc without a card present. I want to configure certain parts of the reader before reading a card.
Thanks in advance.
-----Edit-----
As FPGA Warrior mentioned I need to use SCardControl to send APDU commands to the card reader.
The steps I've gotten so far:
Connect to 'card' with SCardConnect with SCARD_SHARE_DIRECT and SCARD_PROTOCOL_UNDEFINED. This will return as success and give you the card handle.
_lastError = SCardConnect(_hContext, _cardReaderName, dwShareMode, dwPreferredProtocols, ref phCard, ref _activeProtocol);
Returns: 0 and what looks like a valid _hCard handle.
I then call SCardControl
_lastError = SCardControl(phCard, CTL_code(3500), txBytes, (uint)txByte.Length, out rxBytes, (uint)rxAttr.Length, out rxLen);
I now get the error ERROR_INVALID_HANDLE (0x6). So it seems that my SCardConnect does not return a valid handle, even thou it does not return an error.
As a side note to use PC_to_RDR_Escape mode on the device you might need to edit the registry to turn it on if the drivers you installed does not allow it.
https://msdn.microsoft.com/en-us/library/windows/hardware/dn653571%28v=vs.85%29.aspx

I'm not sure why is configuring a reader is made by sending APDUs to a card. It should not be that way. SCardTransmit is for sending command to a card, and it will not work if there is no card (unless you hack the driver so it lies that there is actually a card inserted).
You might be looking for one of these APIs:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa375369(v=vs.85).aspx
It gives more direct acces to your reader / card.
Specifying that what configurations you wish to set on the reader might increase the change to get an answer that helps you.

I was able to do so using perl binding with those parameters :
#connect witouth card in
$hCard = new Chipcard::PCSC::Card($hContext, $ReadersList[0], $Chipcard::PCSC::SCARD_SHARE_DIRECT, $Chipcard::PCSC::SCARD_PROTOCOL_RAW);
#send any adpu
$cmd = Chipcard::PCSC::ascii_to_array("FF 00 40 F0 04 05 05 03 03");
$hCard->Transmit($cmd);

I had a similar experience calling SCardTransmit after SCardConnect (receiving ERROR_INVALID_HANDLE <0x6> from SCardTransmit).
As an experiment, putting Thread.Sleep(100) after SCardTransmit seemed to change the error code from 0x6 to SUCCESS after the sleep statement (as viewed in debugger). This is not a solution but a hint in the right direction. Writing thread safe code to process the statements after SCardControl would be a better way.
The following link is a good reference:
https://www.csharpstar.com/csharp-race-conditions-in-threading/

Simple way is to only switch on/off Smart card reader is to call SCardEstablishContext for connecting to reader.
Note : This will not connect to Smartcard:
/// <summary>
/// Native SCardEstablishContext function from winscard.dll
/// </summary>
/// <param name="dwScope"></param>
/// <param name="pvReserved1"></param>
/// <param name="pvReserved2"></param>
/// <param name="phContext"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError=true)]
internal static extern int SCardEstablishContext(UInt32 dwScope,
IntPtr pvReserved1,
IntPtr pvReserved2,
IntPtr phContext);
To release Reader: this will power off /Release reader handle from the current process.
Note : does not have any relation to the smart card.
/// <summary>
/// Native SCardReleaseContext function from winscard.dll
/// </summary>
/// <param name="hContext"></param>
/// <returns></returns>
[DllImport("winscard.dll", SetLastError=true)]
internal static extern int SCardReleaseContext(UInt32 hContext);

Related

Select Java Card Applet and return 0x61XX rather than 0x9000

I would like my java card applet to emulate our legacy non-java card (native OS) in our organization. The following is the targeted behaviour of the applet:
Select the applet (A4) and return 0x61XX.
Use GET RESPONSE (C0) to read the response
Protocol is T1.
My sample java card is from NXP compatible with JCRE 2.2.2. In my code,
//dataLen is 10 bytes
if (selectingApplet()){
apdu.setOutgoing();
apdu.setOutgoingLength((short)dataLen);
apdu.sendBytesLong(data, (short)0, dataLen);
ISOException.throwIt((short)(ISO7816.SW_BYTES_REMAINING_00 + dataLen)
}
I loaded my applet into the test card. The following is the result:
Select applet
Result: 0x610A
GET RESPONSE
Result: 0x6982
What could be wrong here ? What is the proper way of achieving this if this is even possible with java card ?
I don't think this is possible. The differences between T=0 and T=1 are handled by the Java card framework. GET RESPONSE is specific to T=0.
That means that the 61XX would be generated automatically when using T=0. And of course that the response of SELECT for INSTALL should be automatically returned - unless if the applet thrown an exception that generates a status word, in which case it is likely disregarded.
Similarly, I would expect the framework to catch the GET RESPONSE early, before you can do anything with it. The only thing you could try is to handle the GET RESPONSE yourself and hope the OS passes the APDU along.
But I think the best way of doing this is to configure the chip to use T=0. Then ISO case 4 commands (response and command data) should automatically use GET RESPONSE.

Is it possible to scan barcodes into a process in the background?

I'm making a gym management web app that handles sign-ins. Members have a barcode on a tag that they scan when they arrive to the gym.
I've heard that most barcode scanners simply act as a keyboard. This would require the scanning-in page to be open and in the foreground when a barcode is scanned.
If it's just a keyboard, how would I send the barcode scanner input to a single background process running on the computer, and have it ignore by all processes that may be in focus?
You're right that most scanner can support HID in keyboard emulation, but that's just the start.
If you want to have a bit more control over the data you can use a scanners that support the OPOS driver model.
Take a look at Zebra's Windows SDK to have a overview of the things that you can do. It may be a better solution than try to steal the barcode data coming in the OS as a keyboard entry to the foreground app.
Disclaimer: I work for Zebra Technologies
Other Barcode scanner vendor support a similar driver model.
I found an interesting post with a simple solution:
On the form constructor
InitializeComponent():
this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.Form1_KeyPress);
Handler & supporting items:
DateTime _lastKeystroke = new DateTime(0);
List<char> _barcode = new List<char>(10);
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
// check timing (keystrokes within 100 ms)
TimeSpan elapsed = (DateTime.Now - _lastKeystroke);
if (elapsed.TotalMilliseconds > 100)
_barcode.Clear();
// record keystroke & timestamp
_barcode.Add(e.KeyChar);
_lastKeystroke = DateTime.Now;
// process barcode
if (e.KeyChar == 13 && _barcode.Count > 0) {
string msg = new String(_barcode.ToArray());
MessageBox.Show(msg);
_barcode.Clear();
}
}
Credits: #ltiong_sh
Original post: Here
Use RawInput API (https://www.codeproject.com/Articles/17123/Using-Raw-Input-from-C-to-handle-multiple-keyboard#_Toc156395975) and check device ID for incoming keystrokes. Different devices have different IDs. You can also block keystrokes from scanner from reaching your application and interfering with input fields.
One thing you might want to add is option for user to identity which device is used as a barcode scanner. I did it by asking user to test-scan barcode with scanner on first application startup or in settings.
Works with any barcode scanner which outputs keystrokes.

How can I connect a EV3 mindstorms via bluotooth to a unity game using unityscript?

I am making a race game in Unity with Unityscript and I made a steer with the lego mindstorms EV3 robot. I let te robot send information by bluetooth to the game, but I can't find how I can do that.
I already have the code for the bluetooth running and working a C#, but know I need to know how to translate it to unityscript.
I already tried to find it on google, but I only seem to get some software to hack the robot, but not to make code in unityscript for connecting the steer.
Under here stands the C# code:
// EV3: The EV3Messenger is used to communicate with the Lego EV3.
private EV3Messenger ev3Messenger;
// EV3: Create an EV3Messenger object which you can use to talk to the EV3.
ev3Messenger = new EV3Messenger();
// EV3: Connect to the EV3 serial port over Bluetooth.
// If the program 'hangs' on a call to ev3Messenger.Connect,
// then your EV3 is not paired with your PC yet/anymore.
// To pair: Remove the EV3 from the Windows Bluetooth device list and add it again.
ev3Messenger.Connect("COM3"); // Hardcoded serial port: put the serial port
// of the Bluetooth connection to your EV3 here!
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// Unload any non ContentManager content here
// EV3: Disconnect
if (ev3Messenger.IsConnected)
{
ev3Messenger.Disconnect();
}
}
// EV3: send Brake message to mailbox with name "MakeNoise"
if (ev3Messenger.IsConnected)
{
ev3Messenger.SendMessage("MakeNoise", "Brake");
}
// Game can be controlled by both the arrow keys and the Steer, gas and brake paddle of the connected EV3
UpdatePaddlePositionUsingKeys();
UpdatePaddlePositionUsingEV3();
base.Update(gameTime);
}
///Steer update
private void UpdatePaddlePositionUsingEV3()
{
if (ev3Messenger.IsConnected)
{
// EV3: Receive a new command from mailbox "COMMAND" of the EV3
// and use it to change the direction of the paddle or to exit the game.
EV3Message message = ev3Messenger.ReadMessage();
if (message != null
&& message.MailboxTitle == "Command")
{
if (message.ValueAsText == "")
{
}
{
ev3Messenger.Disconnect();
Exit();
}
}
}
}
I hope that you know where I can find how I can do this or even help me further.
If you want the original code for a small pong game where I got my inspiration from, just comment it.
I hope you can help me.
Here are some useful links with documentation on the EV3 firmware :
Firmware Documentation
LMS2012 Documentation
HDK/SDK
In particular, you need to learn how to send direct commands and then use that to read and write bluetooth mailboxes.
For communicating with the COM port itself using javascript, just do a little searching. For example, I found this SO question which has quite a few different ideas.
As part of c4ev3, We open-sourced our EV3 uploader, which can also be used to send connection-agnostic commands to the device.
Here is how you would move the motors in Perl (Complete version):
use IPC::Open2;
print open2(\*EV3OUT, \*EV3IN, "ev3 tunnel") or die "couldn't find: %!";
print EV3IN "0900xxxx8000 00 A3 00 09 00\n";
print EV3IN "0C00xxxx8000 00 A4 00 09 50 A6 00 09\n";
This would probe for an EV3 accessible over USB, Bluetooth or WiFi and connect to it, then send the direct messages associated with turning the motors. For more information on the direct commands protocol check out LEGO's Communication Developer Manual and David Lechner's answer.
Alternatively, you can write a C program for the EV3 with c4ev3 and communicate with that. That way you got a nicer looking C-API you can use.

How can I select an audio output device in directshow

I was wondering how I can select the output device for audio in directshow. I am able to get available audio output devices in directshow. But how can I make one of these to be audio output device. Its always going for the default audio device. I want to be able to output audio on my choice of device. I have been struggling through google but couldn't find anything useful. All I could get was this link but it doesn't really solve my problem.
Any help will be really helpful for me.
First off, if you're not using DirectShow .NET (DirectShowLib), get that here: It serves as a (very complete) interface between unmanaged DirectShow and C#
What follows is a pretty simple example of how to play an audio file, to the desired audio device
using DirectShowLib;
private IGraphBuilder m_objFilterGraph = null;
private IBasicAudio m_objBasicAudio = null;
private IMediaControl m_objMediaControl = null;
private void playAudioToDevice(string fName, int devIndex)
{
object source = null;
DsDevice[] devices;
devices = DsDevice.GetDevicesOfCat(FilterCategory.AudioRendererCategory);
DsDevice device = (DsDevice)devices[devIndex];
Guid iid = typeof(IBaseFilter).GUID;
device.Mon.BindToObject(null, null, ref iid, out source);
m_objFilterGraph = (IGraphBuilder)new FilterGraph();
m_objFilterGraph.AddFilter((IBaseFilter)source, "Audio Render");
m_objFilterGraph.RenderFile(fName, "");
m_objBasicAudio = m_objFilterGraph as IBasicAudio;
m_objMediaControl = m_objFilterGraph as IMediaControl;
m_objMediaControl.Run();
}
It is up to user to manage audio devices and choose a primary device (such as via Control Panel applet). You can find ways to switch devices programmatically in Windows XP, however in Vista+ it is impossible without interactive user action by design.
See also Larry's answer here: How to change default sound playback device programmatically?
UPDATE: The mentioned above refers to modifying system configuration trying to alter default audio output device. An application is however not limited to default device only. Instead, it can enumerate available devices (see Using the System Device Enumerator + CLSID_AudioRendererCategory) and then create an instance of renderer for specific device with BindToObject call. From there on, it is a regular filter, just bound internally to device of interest.

How to unblock virtual serial ports (in association with 32feet.Net and EMDK)?

I do need a virtual serial port since a program#1 has to set up a bluetooth connection for a second program (program#2) that uses System.IO.Ports.SerialPort, don't I? It isn't a requirement providing that program#1 and #2 run concurrently using the same serial port.
32Feet.NET: Ok. But I get "No ports available" if I start the SuD 7 times (one after another). COM9 -> COM7 -> COM5 -> COM4 -> COM2 -> COM0 -> "No ports available".
program#1 invokes
bdi.SetServiceState(BluetoothService.SerialPort, true)
32feet.Net creates Key in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Bluetooth\Serial\Ports
32feet.Net calls
RegisterDevice(portPrefix, portIndex, "btd.dll", ref pep);
program#2: this.comX.Open(); ... this.comX.Close();
EMDK: An IndexOutOfRangeException is thrown if I start the SuD 7 times (one after another). COM2 -> COM4 -> COM5 -> COM6 -> COM7 -> COM9 -> IndexOutOfRangeException.
program#1: I'm using LocalComPort and HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Bluetooth\Serial\Ports isn't updated.
program#2: this.comX.Open(); ... this.comX.Close();
What is the reason? There's no process#1 and process#2 left.
Once you've set the port up one time why do you ever have to do it again? With SetServiceState the configuration is set in the Registry for ever and thus will be there for ever, e.g. after a reboot... Presumably the same is true for the method you are using in EMDK. I don't recognise that name (maybe it is Motorola only) but on my M3 Sky I have used the BTExplorerApi and it has a for-ever and a not-for-ever flag in the port-set-up function.
On 32feet.NET with the MSFT stack. (Note: Peter was the expert in this not me). :-,( As I understand it if you use class BluetoothSerialPort, that will create a port that's configured temporary (not over reboot etc). Maybe that's what you want?
Once you've set the port up one time why do you ever have to do it again?
Use case scenario: Mr. X uses one mobile device and one serial RS232 Bluetooth adapter to communicate with several units. But for the seventh there won't be any virtual serial port left.
I was using 32feet.Net for ES400 trouble-free. For MC55, MC35 the phenomena under discussion appears. And that was the reason why I created this question.
I don't know what's going on under the hood yet. But as far as EMDK concerned: if the connection isn't needed any longer, you have to unpair the device.
I'm using EMDK for Motorola ES400 and MC55:
/// <summary>
/// Removes the pairing, turns Bluetooth off and disables the bluetooth object.
/// </summary>
public void ReleaseLink(){
try{
this.remoteDevice.UnPair();
this.bluetooth.Dispose();
I'm using 32feet.NET for Motorola MC35 (BluetoothSerialPort that invokes RegisterDevice):
if (!bdi.Authenticated)
{
string pair = rd.Pin;
paired = BluetoothSecurity.PairRequest(bdi.DeviceAddress, pair);
if (!paired)
{
return;
}
}
spp = BluetoothSerialPort.CreateClient(new BluetoothEndPoint(remoteAddress,BluetoothService.SerialPort));
public void ReleaseLink()
{
try
{
BluetoothSecurity.RemoveDevice(spp.Address);
spp.Dispose();

Resources