C_Login fails in PKCS11 in C - c

Simple issue, but i don't know how to unlock USB Token(epass2003) ,I have try to read PKCS 11 but have no idea how to implement C_Login function for execution in c ,when i am using command line tool (Linux)to do that token is working perfectly fine but with c its not working I have used user type as CKU_USER, Can anyone have knowledge about this, please help

you have to check the return values from the PKCS functions to see if there has been any errors. Try this way and see what happen. If the return code from C_login() is CKR_PIN_LOCKED, then it is clear that you should unlock your card.
CK_RV ret;
ret = C_OpenSession(slot, CKF_SERIAL_SESSION, NULL_PTR, NULL_PTR, &session);
if (ret != CKR_OK){
error_message(ret);
return;
}
readPIN("Intro PIN: ", pin, 4);
ret = (f_C_Login)(hSession,CKU_USER, (unsigned char *) pin,strlen(pin));
if (ret != CKR_OK){
closeSessions(slot);
error_message(ret);
return;
}

A token can get locked due to a certain number of failed login (for TrustKey it is 10). There are provider specific utilities to unlock tokens. You could check Feitian site. There is some pointer to this kind of problem in Gooze forum (though not exactly). Your problem looks quite like a token lock problem.

Related

Monitor flashing when running a Windows SendInput API

Well, I certainly should go to python since I did several functions of this type, keyboard event and mouse event, but decide to try to learn the windows api.
My goal is to know when button 1 of the mouse is pressed.
I created this file in a very beginner way, it returns in mouseData only 0.
The curious thing is that whenever I run it, it flashes my monitor at short intervals in blinks, but between 1 second with it off. Very strange that, execution is not viable.
Could someone help me understand and try to execute to see if it is only here.
Code:
int main()
{
DWORD mouseData = 0;
MOUSEINPUT tagMouse;
tagMouse.dx = 0;
tagMouse.dy = 0;
tagMouse.mouseData = mouseData;
tagMouse.dwFlags = MOUSEEVENTF_XDOWN;
tagMouse.dwExtraInfo = 0;
INPUT tagInput;
tagInput.type = INPUT_MOUSE;
tagInput.mi = tagMouse;
while (true) {
if (GetAsyncKeyState(VK_DELETE)) break;
SendInput(1, &tagInput, sizeof(INPUT));
printf("KEYWORD: %d\n", mouseData);
Sleep(500);
}
system("pause");
return 0;
}
I can reproduce your reported 'symptoms' - and the effect is really brutal!
Now, while I cannot offer a full explanation, I can offer a fix! You have an uninitialized field in your tagMouse structure (the time member, which is a time-stamp used by the system). Setting this to zero (which tells the system to generate its own time-stamp) fixes the problem. So, just add this line to your other initializer statements:
//...
tagMouse.dwExtraInfo = 0;
tagMouse.time = 0; // Adding this line fixes it!
//...
Note: I, too, would appreciate a fuller explanation; however, an uninitialized field, to me, smells like undefined behaviour! I have tried a variety of other values (i.e. not zero) for the time field but haven't yet found one that works.
The discussion here on devblogs may help. This quote seems relevant:
And who knows what sort of havoc that will create if a program checks
the timestamps and notices that they are either from the future or
have traveled back in time.

How do I get the disk drive serial number in filter driver?

I write a driver in windows, and I need disk drive serial number, for user mode I found this ansver.
My question is it possible to translate the above code to kernel mode, and how? Is WMI query available in filter driver? Sample code can greatly help.
EDIT:
I found here this code, but how I rewrite him for get serial number?
void GetSmbios()
{
NTSTATUS status;
GUID smbiosGUID = SMBIOS_DATA_GUID; // defined in wmiguid.h
PVOID wmiObject = NULL;
PWNODE_ALL_DATA dataBuffer;
ULONG bufferSize;
int TAG_SMBIOS = 'smbi';
//
// Get a WMI block handle to the SMBIOS_DATA_GUID
//
status = IoWMIOpenBlock((GUID *)&smbiosGUID, WMIGUID_QUERY,
&wmiObject);
if (!NT_SUCCESS(status))
{
return status;
}
//
// Determine how much space is required for the data
//
status = IoWMIQueryAllData(wmiObject, &bufferSize, NULL);
if (status != STATUS_BUFFER_TOO_SMALL)
{
ObDereferenceObject(wmiObject);
return status;
}
//
// Allocate the necessary storage. This space must come out of NP-pool
//
dataBuffer = ExAllocatePoolWithTag(
NonPagedPool,
bufferSize,
TAG_SMBIOS);
if (dataBuffer == NULL)
{
ObDereferenceObject(wmiObject);
return STATUS_INSUFFICIENT_RESOURCES;
}
}
After allocating memory, I believe you need to call IoWMIQueryAllData() again, this time passing dataBuffer.
SMBIOS doesn't seem related to disk drives, so you'll want a different GUID to pass to IoWMIOpenBlock(). Perhaps this one ({BF253431-1E4D-4F57-00E7-64B2CACC801E}), since your user-mode example and others query Win32_PhysicalMedia to get SerialNumber.
However, this references a (presumably user-mode) DLL that is the provider for Win32_PhysicalMedia. So this may not be accessible in kernel-mode.
But it also gives a hint how to get the information from kernel-mode: IOCTLs. It mentions IOCTL_SMART_GET_VERSION, which should be just SMART_GET_VERSION, and here's an example:
(in user-mode, but you should be able to do similar from kernel-mode using ZwDeviceIoControlFile()). Note it follows up with another ioctl command, SMART_RCV_DRIVE_DATA, to get the serial number.
Another ioctl that sounds promising (and more general) is IOCTL_STORAGE_QUERY_PROPERTY, with the input STORAGE_PROPERTY_QUERY.PropertyId set to StorageDeviceProperty, so the output will be a STORAGE_DEVICE_DESCRIPTOR structure, which has field SerialNumberOffset:
Specifies the byte offset from the beginning of the structure to a null-terminated ASCII string that contains the device's serial number. If the device has no serial number, this member is zero.
FILE_FS_VOLUME_INFORMATION contains field VolumeSerialNumber. This data structure might be retrieved with ZwQueryVolumeInformationFile(... FileFsVolumeInformation).
That requires a handle to the volume or a file/directory in the volume. If that's not feasible, but you have a DEVICE_OBJECT, you might try building your own IRP with IRP_MJ_QUERY_VOLUME_INFORMATION and sending it with IoCallDriver(), though I don't know if that's sanctioned -- the docs say such a "request is sent by the I/O Manager."

InternetReadFileEx gives 10035 and 1008 errors

I am trying to write an Asyncronous Wininet application. I read the data in my callback function in case of INTERNET_STATUS_REQUEST_COMPLETE and I handle the ERROR_IO_PENDING errors as well. But after some data read from internet, InternetReadFileEx function gives me 10035=WSAEWOULDBLOCK (A non-blocking socket operation could not be completed immediately) error. After that error I call InternetReadFileEx again and this time it gives me 1008=ERROR_NO_TOKEN (An attempt was made to reference a token that does not exist.) error. I think my design is not correct, and I receive these error because of that.
Here is a snippet of my code:
case INTERNET_STATUS_REQUEST_COMPLETE:
{
BOOL bAllDone= FALSE;
DWORD lastError;
do
{
//Create INTERNET_BUFFERS
char m_pbReadBuffer[4096];
INTERNET_BUFFERS BuffersIn;
ZeroMemory(&BuffersIn, sizeof(INTERNET_BUFFERS));
BuffersIn.dwStructSize = sizeof(INTERNET_BUFFERS);
BuffersIn.lpvBuffer = m_pbReadBuffer;
BuffersIn.dwBufferLength = 4096;
InternetReadFileEx(ReqContext->File, &BuffersIn, IRF_ASYNC, 1);
//HERE I GOT THOSE 10035 and 1008 ERRORS
lastError = GetLastError();
if(lastError == 997) // handling ERROR_IO_PENDING
break;//break the while loop
//append it to my ISTREAM
(ReqContext->savedStream)->Write(BuffersIn.lpvBuffer, BuffersIn.dwBufferLength, NULL);
if (BuffersIn.dwBufferLength == 0)
bAllDone = TRUE;
}while(bAllDone == FALSE);
//delete[] m_pbReadBuffer;
if(bAllDone == TRUE && lastError== 0)
{
//these are for passing the ISTREAM to the function which calls "InternetOpenUrl"
LARGE_INTEGER loc;
loc.HighPart = 0;
loc.LowPart = 0;
ReqContext->savedStream->Seek(loc, STREAM_SEEK_SET, NULL);
ReqContext->savedCallback->OnUrlDownloaded(S_OK, ReqContext->savedStream); //Tell silverlight ISTREAM is ready
ReqContext->savedStream->Release();
ReqContext->savedCallback->Release();
InternetCloseHandle(ReqContext->File);
InternetSetStatusCallback(ReqContext->Connection, NULL);
InternetCloseHandle(ReqContext->Connection);
delete[] ReqContext;
}
}
break;
Can anyone give me a hand to correct that?
Thanks everyone helping...
GetLastError() is only meaningful if InternetReadFileEx() (or any other API, for that matter) actually fails with an error. Otherwise, you will be processing an error from an earlier API call, giving your code a false illusion that an error happened when it really may not have. You MUST pay attention to API return values, but you are currently ignoring the return value of InternetReadFileEx().
Worse than that, though, you are using InternetReadFileEx() in async mode but you are using a receiving buffer that is local to the INTERNET_STATUS_REQUEST_COMPLETE callback handler. If InternetReadFileEx() fails with an ERROR_IO_PENDING error, the read is performed in the background and INTERNET_STATUS_REQUEST_COMPLETE will be triggered when the read is complete. However, when that error occurs, you are breaking your loop (even though the read is still in progress) and that buffer will go out of scope before the read is finished. While the reading is still in progress, the receiving buffer is still on the stack and InternetReadFileEx() is still writing to it, but it may get re-used for other things at the same time because your code moved on to do other things and did not wait for the read to finish.
You need to re-think your approach. Either:
remove the IRF_ASYNC flag, since that is how the rest of your callback code is expecting InternetReadFileEx() to behave.
re-write the code to operate in async mode correctly. Dynamically allocate the receive buffer (or at least store it somewhere else that remains in scope during the async reading), don't call IStream::Write() unless you actually have data to write (only when InternetReadFileEx() returned TRUE right away, or you get an INTERNET_STATUS_REQUEST_COMPLETE event with a success code from an earlier InternetReadFileEx()/ERROR_IO_PENDING call), etc.
There are plenty of online examples and tutorials that show how to use InternetReadFileEx() in async mode. Search around.

How to retrieve starting address of a thread in windows?

I'm working on a mini windows process explorer in C, I have a handle to a thread.
How can I retrieve starting address of that thread? Something like this:
Such question was already asked a few days ago. Here is a sample solution:
DWORD WINAPI GetThreadStartAddress(HANDLE hThread)
{
NTSTATUS ntStatus;
HANDLE hDupHandle;
DWORD dwStartAddress;
pNtQIT NtQueryInformationThread = (pNtQIT)GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQueryInformationThread");
if(NtQueryInformationThread == NULL)
return 0;
HANDLE hCurrentProcess = GetCurrentProcess();
if(!DuplicateHandle(hCurrentProcess, hThread, hCurrentProcess, &hDupHandle, THREAD_QUERY_INFORMATION, FALSE, 0)){
SetLastError(ERROR_ACCESS_DENIED);
return 0;
}
ntStatus = NtQueryInformationThread(hDupHandle, ThreadQuerySetWin32StartAddress, &dwStartAddress, sizeof(DWORD), NULL);
CloseHandle(hDupHandle);
if(ntStatus != STATUS_SUCCESS)
return 0;
return dwStartAddress;
}
Source: http://forum.sysinternals.com/how-to-get-the-start-address-and-modu_topic5127_post18072.html#18072
You might have to include this file: http://pastebin.com/ieEqR0eL
Related question: How to add ntdll.dll to project libraries with LoadLibrary() and GetProcAddress() functions?
NtQueryInformationThread with ThreadQuerySetWin32StartAddress. Another possibility is to walk the thread's stack with StackWalk64.
If you only need the start address, NtQueryInformationProcess is a lot simpler. Even with fairly terse coding, walking the stack takes a couple hundred lines of code or so.
You should be able to get a stack trace with StackWalk64 or a related function, and then parse it with the dbghelp.dll .
This CodeProject article explains it all in detail:
http://www.codeproject.com/KB/threads/StackWalker.aspx

C \ UNIX \ strcmp first use is wrong, correct all other times

hey all i wrote some code on microsoft VS which is suppose to compare passwords entered to ones stored in database and return approved or denied...
it worked perfectly good on windows, but after converting to UNIX (using eclipse) a funny thing happend - always, the first call to this function doesnt return the approved value when it should, but calling for the function again with exactly the same params returns approved... as desired.
after debugging i am pretty sure the problem is in the "strcmp", that returns false on the first run and true in all other runs on the exact same parameters.
anyone has an idea on what could be the problem??
an example for a commands:
add jt 111
// adding the password to the DB
login jt 111
denied
login jt 111
approved
void login_helper(char *user, char *password){
int found = 0;
int i;
for (i=0 ; i<space ; i++){
if (strcasecmp(data[i].name,user) == 0) {
found = 1;
if (strcmp(data[i].hash ,Md5FromString(password)) == 0)
{
printf("approved.\n");
break;
}
else {
printf("denied.\n");
break;
}
}
}
if (found == 0) printf("denied.\n");
}
I predict that the call to Md5FromString(password) returns a pointer to a buffer that's no longer valid when the Md5FromString() function returns. That would mean that you're running into undefined behavior, and getting lucky in some cases and unlucky in others.
Post the code to Md5FromString().
I'd really doubt there's any problem in strcmp(). :-)
(There's an excellent book on SW development called "The Pragmatic Programmer", by Andrew Hunt and David Thomas, which has a tip regarding debugging called "'select' is not broken", which ultimately means that it's really unlikely that a basic system function (e.g. select() or strcmp()) is broken.)
Did you try printf'ing the contents of 'data[i].hash' and the value returned by 'Md5FromString(password)' right before strcmp()?
Something like:
char *md5;
...
md5 = Md5FromString(password);
printf("i: %d, hash: %s, md5: %s\n", i, data[i].hash, md5);
if (strcmp(data[i].hash, md5) == 0)
{
...
Also, who allocates memory for function Md5FromString()? Can you send the code for Md5FromString()?
Cheers,
Paulo

Resources