Use PKCS#11 in Visual Studio - c

I need to connect to a token using the standard PKCS#11.
In my C program, wrote with Visual Studio, I included PKCS#11 headers, downloaded from RSA site and some macros.
//define macros
#define CK_PTR *
#define CK_DEFINE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType (* name)
#define CK_CALLBACK_FUNCTION(returnType, name) returnType (* name)
#ifndef NULL_PTR
#define NULL_PTR 0
#endif
#include "pkcs11.h"
int main(int argc, char * argv[]) {
[..]
C_Initialize(NULL_PTR);
[..]
When i build it, i get "undefined reference to C_Initialize". The same error for all the pkcs11 function I used.
In the program directory there are also the other pkcs11 headers. What is the wrong with it?

For static linking you need to have a corresponding .lib file. You can have it if you link the application with the SDK of particular hardware device.
The generic approach is to load the DLL given by the end user dynamically. To do this your code needs to use LoadLibrary() and GetProcAddress() Windows API functions to obtain addresses of each function of the library (yes, there are more than 50 functions there if memory serves).

You're not linking with whatever object file or library that C_Initialize function is defined in.

Related

DLL dependency to static library

I currently build a purely static library MainLib for our customers that contains all symbols so that they can intrgrate it into their program. For several reasons, I now need to deliver a DLL version of MainLib that contains parts of the symbols alongside a static library FeatureLib that contains the remaining symbols. One reason is that we want to avoid bad guys using our software by simply stealing the DLL that is provided via the program of our customer. This wouldn't work if parts of the symbols are integrated within the calling software via a static library. The user of the package shall only be able to use the DLL if he added the symbols of FeatureLib into his application.
For Linux, I can make this work like a charm,i.e. the symbol doFeature() is not within libMainLib.so, but I don't succeed on this for Windows.
CMakeLists.txt:
cmake_minimum_required(VERSION 3.0)
project(MainLib)
add_library(FeatureLib STATIC src/FeatureLib.c)
target_include_directories(FeatureLib PUBLIC include
PRIVATE src)
add_library(MainLib SHARED src/MainLib.c)
target_include_directories(MainLib PUBLIC include
PRIVATE src)
# I don't want to include symbols from FeatureLib into shared MainLib
#target_link_libraries(MainLib PRIVATE FeatureLib)
add_executable(MainLibDemo src/demo.c)
target_link_libraries(MainLibDemo MainLib FeatureLib) #resolve symbol doFeature()
FeatureLib.h:
extern int doFeature(int input);
MainLib.h:
extern __declspec(dllexport) int MainLib(int input);
FeatureLib.c:
#include "FeatureLib.h"
int doFeature(int input) {return 4;}
MainLib.c:
#include "FeatureLib.h"
#include "MainLib.h"
__declspec(dllexport) int MainLib(int input)
{
if (input > 2) {
return doFeature(input);
} else {
return doFeature(0);
}
}
demo.c:
#include <stdio.h>
#include <stdlib.h>
#include "MainLib.h"
int main(int argc, char **argv)
{
if(argc > 1)
return MainLib(atoi(argv[1]));
else
return 0;
}
With this, I get the following compilation error:
"C:\Daten\tmp\DemoProject\simple\build\ALL_BUILD.vcxproj" (Standardziel) (1) ->
"C:\Daten\tmp\DemoProject\simple\build\MainLib.vcxproj" (Standardziel) (4) ->
(Link Ziel) ->
MainLib.obj : error LNK2019: unresolved external symbol _doFeature referenced in function _MainLib [C:\Daten\tmp\DemoProject\simple\build\MainLib.vcxproj]
C:\Daten\tmp\DemoProject\simple\build\Debug\MainLib.dll : fatal error LNK1120: 1 unresolved externals [C:\Daten\tmp\DemoProject\simple\build\MainLib.vcxproj]
0 Warnung(en)
2 Fehler
Is this even possible with Windows? What do I have to do to make it work and how can I verify it other than not linking FeatureLib to MainLibDemo. Any ideas are very welcome.
Kind regards,
Florian
The way you do it under Linux will not work under Windows
because dynamic linking works differently here.
Here is one strategy that could work.
In MainLib.dll code, instead of directly calling doFeature
you need to define a global pointer variable of proper function
pointer type and use it to call the function.
This will allow to build MainLib.dll without errors.
Now you need to set this pointer variable. One way would be:
Add exported function to MainLib.dll that takes pointers
to all functions that the DLL needs from the executable.
In FeatureLib.lib code add an initialisation function
that the application will need to call before using
your DLL which will pass pointers to its peers to the DLL.
This is basically the way most programs with plugins use to
give the plugins access to their facilities.
Another way would be to (Warning! I have not tested this specific
solution):
Declare the functions in FeatureLib.lib as exported
with __declspec(dllexport). This way they will be exported
from executable.
In MainLib.dll before first using the pointers use
GetModuleHandle and GetProcAddress to obtain the pointers.
It would best be done in some initialisation function for the
library. Otherwise you need to take care to avoid race conditions.
Hope this will help.
Though I do not think your copy protection scheme will work.
Andrew Henle is right in his comment: it is not hard
to extract the needed code from one executable and include it
in another.

PGDLLIMPORT and PostgreSQL C hooks

I've been using PostgreSQL hooks for some time now, and yesterday I wanted to try to add my own hook to test something(and for fun).
So I looked up ExecutorStart_hook to see what are the things I would need to do in order to get my own hook into PostgreSQL.
In execMain.c it is pretty straight forward, first define the hook
ExecutorStart_hook_type ExecutorStart_hook = NULL;
then use it in ExecutorStart(...);.
In executor.h we define the hook type first, and then we import the hook variable.
typedef void (*ExecutorStart_hook_type) (QueryDesc *queryDesc, int eflags);
extern PGDLLIMPORT ExecutorStart_hook_type ExecutorStart_hook;
Where are importing this hook variable from? I don't see it anywhere else except in execMain.c, and I don't see a PGDLLEXPORT there.
On non-windows platforms, that does nothing.
On windows, PGDLLIMPORT's meaning changes based on whether the PostgreSQL server is being compiled, or an extension. The headers are written from the perspective of an extension, which is why it says PGDLLIMPORT.
If you look at the definition of PGDLLIMPORT in src/include/port/win32.h:
#ifdef BUILDING_DLL
#define PGDLLIMPORT __declspec (dllexport)
#else /* not BUILDING_DLL */
#define PGDLLIMPORT __declspec (dllimport)
#endif
... you'll see that if BUILDING_DLL is set, we expand it to __declspec(ddlexport). So it exports the symbol from the server binary. We only set BUILDING_DLL when compiling postgres.exe; its name a bit unfortunate. It's like that because on Windows you're usually exporting symbols from DLLs for use in applications, not vice versa like in postgres.
If BUILDING_DLL is not set, we define PGDLLIMPORT to __declspec(dllimport), importing the symbol from the server binary into whatever's linking to it.
So ... when postgres includes executor.h it exports the symbol. When you include executor.h in your extension DLL project, it imports the symbol.
All this is necessary because of how DLL linkage works on win32/PE. On ELF platforms (Linux, BSD, etc) and Mach-O (Mac OS X), none of it is necessary.

Compiling library version into .so file

I have a C linux API library that I distribute both to end users and to servers. When a user needs to use this library, they compile and build a .so file that they send to our servers to be run. I would like a way to compile in the version number of the library into their .so file such that my server can check what version they compiled on. This way if the server is incompatible with the user's .so file, I can refuse to load the library. I'm not sure what options I even have to achieve this and was hoping for any type of suggestion. Please let me know if any more information would be helpful in solving this issue.
It's common for libraries to have a getLibraryVersion function that returns some constant value, be it a string, integer, or whatever. This would get you the version you linked against (i.e. your .so version). You could have an additional macro to get the version you compiled against (i.e. your server's version).
For example, SDL's API has a version struct and the following function defined in one of its headers:
#define SDL_MAJOR_VERSION 1
#define SDL_MINOR_VERSION 2
#define SDL_PATCHLEVEL 15
typedef struct SDL_version {
Uint8 major;
Uint8 minor;
Uint8 patch;
} SDL_version;
/**
* This macro can be used to fill a version structure with the compile-time
* version of the SDL library.
*/
#define SDL_VERSION(X) \
{ \
(X)->major = SDL_MAJOR_VERSION; \
(X)->minor = SDL_MINOR_VERSION; \
(X)->patch = SDL_PATCHLEVEL; \
}
/**
* Use this function to get the version of SDL that is linked against
* your program.
*/
extern void SDL_GetVersion(SDL_version* ver);
In one of your .so's .c files:
void SDL_GetVersion(SDL_version* ver)
{
SDL_VERSION(ver);
}
Example use:
SDL_version compiled;
SDL_version linked;
SDL_VERSION(&compiled);
SDL_GetVersion(&linked);
printf("We compiled against SDL version %d.%d.%d ...\n",
compiled.major, compiled.minor, compiled.patch);
printf("We are linking against SDL version %d.%d.%d.\n",
linked.major, linked.minor, linked.patch);
On a side note; it's a little dangerous to be running somebody else's code on your servers.

How to declare DLL in user32.dll (aka stdcall?) fashion?

I have a third party application that allows you to call C functions from DLL files. Provided sample to this app shows you can call MessageBoxW from user32.dll. It also allows you to call C functions from your DLL files.
I've did a DLL from a file.h file like this:
_declspec (dllexport) void example(int);
and file.c like this:
#include <stdio.h>
#include "file.h"
_declspec (dllexport) void example(int s1)
{
printf("dsa");
}
And compile it with C/C++ Compiler Version 15 from Windows SDK like this:
cl file.c /DLL /LD
And i get proper compilation with DLL file. In DLL functions examiner I see my function. I drop this file into System32 folder and call it from this third party application.
Application finds the file, but is unable to find the function.
I think the cause of the problem is that i declare (or compile) my DLL in other fashion/way/standard that Windows libraries (like user32.dll) because user32.dll works fine.
I've found that the third party app uses this kind of calling functions in DLL:
winapi_abi Used for calling Windows system functions. These are
declared as stdcall on Windows, but do not have mangled names.
So my question is: how to prepare and compile DLL file in the user32.dll fashion (stdcall?) so it will work with third party app?
The easy answer is:
__declspec(dllexport) void __stdcall example(int);
And the same in the implementation, of course.
If you look into windows.h and friends you'll see:
#define WINUSERAPI __declspec(dllexport)
#define WINAPI __stdcall
And then:
WINUSERAPI int WINAPI MessageBoxW(HWND,LPCWSTR,LPCWSTR,UINT);
But if you just define a few functions there is no need for the macros.
Include a .def file to defeat stdcall name decoration. Then you can get rid of the __declspec(dllexport) clutter.
You are not specifying any calling convention in your function declaration, so the compiiler will default to __cdecl, which decorates the exported name. Also, if you compile in C++ instead of C, additional decorating occurs as well. You need to do something like the following in your code to get around all of that:
file.h:
#ifndef fileH
#define fileH
#ifdef _BUILDING_DLL_
#define MYEXPORT __declspec (dllexport)
#else
#define MYEXPORT __declspec (dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
MYEXPORT void __stdcall example(int);
#ifdef __cplusplus
}
#endif
#endif
file.c:
#include <stdio.h>
#define _BUILDING_DLL_
#include "file.h"
void __stdcall example(int s1)
{
printf("dsa");
}
Thank you all. The solution was to add def file with exports, include it in compiler by /DEF:file.def, use Remy version (without #define _BUILDING...) and remove _stdcall.

How do I get a bundle reference from inside of a plugin with carbon?

I'm writing a C++ plugin in Mac OS X using the Carbon framework (yeah, yeah, I know, Apple is deprecating Carbon, but at the moment I can't migrate this code to Cocoa). My plugin gets loaded by a master application, and I need to get a CFBundleRef reference to my plugin so that I can access it's resources.
The problem is, when I call CFBundleGetMainBundle() during my plugin's initialization routines, that returns a reference to the host's bundle reference, not the plugin's. How can I get a reference to my plugin's bundle instead?
Note: I would rather not use anything determined at compile-time, including calling CFBundleGetBundleWithIdentifier() with a hard-coded string identifier.
See this posting on the carbon-dev mailing list, which seems to be a similar situation.
The method given there is
I recommend using CFBundleGetBundleWithIdentifier.
Your plug-in should have an unique identifier; something like
"com.apple.dts.iTunes_plug-in", etc. Look for the CFBundleIdentifier
property in your plug-in's bundle's info.plist.
Note: I would rather not use anything determined at compile-time, including calling CFBundleGetBundleWithIdentifier() with a hard-coded string identifier.
Because that's WET, right?
Here's how you can make that solution DRY.
First, define some macros for this in a header file, like so:
#define MY_PLUGIN_BUNDLE_IDENTIFIER com.example.wiflamalator.photoshop-plugin
#define MY_PLUGIN_STRINGIFY(x) #x
#define MY_PLUGIN_BUNDLE_IDENTIFIER_STRING MY_PLUGIN_STRINGIFY(MY_PLUGIN_BUNDLE_IDENTIFIER)
Import the header file into the code that calls CFBundleGetBundleWithIdentifier. In that code, use CFSTR(MY_PLUGIN_BUNDLE_IDENTIFIER_STRING).
Then, in Xcode, either set that file as your Info.plist prefix header, or (if you already have one) #include it into that header. Finally, in Info.plist, set the bundle identifier to MY_PLUGIN_BUNDLE_IDENTIFIER (in a string value, of course).
Now you have the bundle identifier written in exactly one place (the header), from which the C preprocessor puts it in all the places where it needs to be, so you can look up your own bundle by it using CFBundleGetBundleWithIdentifier.
#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif
#ifdef __APPLE__
// This should be actually defined somewhere else
#define MY_PLUGIN_BUNDLE_IDENTIFIER com.yourbundle.name
// Then all the regular stuff
#define QUOTE(str) #str
#define EXPAND_AND_QUOTE(str) QUOTE(str)
#define MY_PLUGIN_BUNDLE_IDENTIFIER_STRING EXPAND_AND_QUOTE(MY_PLUGIN_BUNDLE_IDENTIFIER)
CFBundleRef mainBundle = CFBundleGetBundleWithIdentifier(CFSTR(MY_PLUGIN_BUNDLE_IDENTIFIER_STRING));
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
char path[PATH_MAX];
if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
{
// error!
}
CFRelease(resourcesURL);
chdir(path);
StoragePaths::setApplicationResourcesDirectory(STR(path));
#endif
Prints the path to the your bundle
Note: For JUCE users, use JucePlugin_CFBundleIdentifier instead of MY_PLUGIN_BUNDLE_IDENTIFIER and you're all set

Resources