How to implement an openssl engine with usb token - cryptography

I an new to crypto and now want to implement the openssl engine ,
i find refernece at
https://github.com/AtmelCSO/cryptoauth-openssl-engine
HOwever, once i implement the eccx08_eckey_meth.c
i encounter error in the
EVP_PKEY_METHOD eccx08_pkey_meth = {
0, // pkey_id
0, // flags
eccx08_pkey_ec_init, // init - pkey_ec_init in ec_pmeth.c
NULL, // copy - pkey_ec_copy in ec_pmeth.c
NULL, // cleanup - pkey_ec_cleanup in ec_pmeth.c
NULL, // paramgen_init
NULL, // paramgen - pkey_ec_paramgen in ec_pmeth.c
eccx08_pkey_ec_keygen_init, // keygen_init - pkey_ec_keygen_init in ec_pmeth.c
eccx08_pkey_ec_keygen, // keygen - pkey_ec_keygen in ec_pmeth.c
NULL, // sign_init
NULL, // sign - pkey_ec_sign in ec_pmeth.c
NULL, // verify_init
NULL, // verify - pkey_ec_verify in ec_pmeth.c
NULL, // verify_recover_init
NULL, // verify_recover
NULL, // signctx_init
NULL, // signctx
NULL, // verifyctx_init
NULL, // verifyctx
NULL, // encrypt_init
NULL, // encrypt
NULL, // decrypt_init
NULL, // decrypt
NULL, // derive_init
#ifndef OPENSSL_NO_ECDH
NULL, // derive - pkey_ec_kdf_derive in ec_pmeth.c
#else
NULL, // derive - pkey_ec_kdf_derive in ec_pmeth.c
#endif
NULL, // ctrl - pkey_ec_ctrl in ec_pmeth.c
NULL // ctrl_str - pkey_ec_ctrl_str in ec_pmeth.c
};
static int eccx08_pkey_meth_nids[] = { NID_id_ATECCX08, 0
};
I cannot call the above struture to use
and i find the problem is here:
int eccx08_pkey_meth_f(ENGINE *e, EVP_PKEY_METHOD **pkey_meth,
const int **nids, int nid)
{
eccx08_debug("eccx08_pkey_meth_f()\n");
if (!pkey_meth) {
//see gost_eng.c:210 for an example
*nids = 0;
return 0;
}
*pkey_meth = (EVP_PKEY_METHOD *)&eccx08_pkey_meth;
return 1;
}
the *pkey_meth = (EVP_PKEY_METHOD *)&eccx08_pkey_meth; was never called?
canyone can help?
thanks

try:
if (!pkey_meth) {
*nids = eccx08_pkey_meth_nids;
return 1; /* return the number of nids your engine supports */
}

Related

How to localize the Authorization Right Description?

I am trying to set a right with a custom description. When calling AuthorizationCopyRights(), I expect to see my localized string but I see the key kDescription. I can confirm that my application is correctly setup for localization by showing the localized string on the NSTextField in the window. I have seen this technical documentation by apple but it seems like I am doing something incorrect? This is a sample code I have written in a Cocoa app to demonstrate it:
#define kRightName "TryingToLocalizePrompt"
- (IBAction) button : (id) sender
{
AuthorizationRef authRef;
OSStatus error = errAuthorizationSuccess;
AuthorizationItem oneRight = { NULL, 0, NULL, 0 };
AuthorizationRights rights = { 1, &oneRight };
AuthorizationFlags flags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagPreAuthorize |
kAuthorizationFlagExtendRights;
if (error == errAuthorizationSuccess) {
error = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, flags, &authRef);
}
if (error == errAuthorizationSuccess) {
error = AuthorizationRightSet(
authRef,
kRightName,
#kAuthorizationRuleAuthenticateAsAdmin,
(__bridge CFStringRef) #"kDescription", // <---- Not localizing?
NULL, // I tried passing CFBundleGetMainBundle()
NULL // I have also tried (__bridge CFStringRef) #"Localizable"
);
}
if (error == errAuthorizationSuccess) {
oneRight.name = kRightName;
error = AuthorizationCopyRights(
authRef,
&rights,
NULL,
kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed,
NULL
);
}
// Testing that localizable.strings file is correctly set into build:
[self.label setStringValue: NSLocalizedString(#"kDescription", NULL)];
error = AuthorizationRightRemove(authRef, kRightName);
}
This is my Localizable.strings file:
/*
Localizable.strings
AuthRight
Created by Brandon Fong on 6/19/21.
*/
"kDescription" = "Hello World!";
Any help or advice is greatly appreciated!

Why does update not update any records?

I am using the OCI functions to update a database table in Oracle but despite the commands all returning success nothing in the database table is changing. It changes if I hard code the Where clause values so I think I might be doing something wrong in the binding code?
If I create the database table as follows:
create table updatebuddTI(i char(10), j int);
insert into updatebuddTI values ('test1',1);
insert into updatebuddTI values ('test2',2);
insert into updatebuddTI values ('test3',3);
and then use the code:
#include "stdafx.h"
#include <string>
#include <oci.h>
#include <stdlib.h>
#define OCI_NOT_NULL 0
#define OCI_VALUE_NULL -1
#define OCI_VALUE_TRUNCATED -2
#define ORACLE_MAX_SESSIONS 30
int _tmain(int argc, _TCHAR* argv[]) {
// OCI handles
OCIEnv *envhp;
OCIError *errhp;
OCIServer *srvhp;
OCISvcCtx *svchp;
OCISession *authp;
OCIStmt *stmtp;
OCIDefine *defnpp;
// Connection information
text* user = (text*)"test";
text* pwd = (text*)"password";
text* sid = (text*)"oracle-server";
char *query = "UPDATE updatebuddTI SET I = 'test3' WHERE J = :1";// :2";
int dataReceivedI[10];
// Fetched data indicators, lengths and codes
ub2 dataReceived_len[10];
ub2 dataReceived_code[10];
sb2 dataReceived_indI[3];
ub2 dataReceived_lenI[3];
ub2 dataReceived_codeI[3];
oratext message[512];
sb4 errcode;
// Allocate environment
int rc = OCIEnvCreate(&envhp, OCI_DEFAULT, NULL, NULL, NULL, NULL, 0, NULL);
ub2 code = OCINlsCharSetNameToId(envhp, (const oratext *)"WE8MSWIN1252");
OCIEnv *envHandle(0);
if(code) {
rc = OCIEnvNlsCreate(&envHandle,
OCI_OBJECT | OCI_THREADED,
NULL,
NULL,
NULL,
NULL,
0,
NULL,
code,
code);
} else {
printf("problem with OCIEnvNlsCreate!\n");
}
// Allocate error handle
rc = OCIHandleAlloc(envhp, (void**)&errhp, OCI_HTYPE_ERROR, 0, NULL);
// Allocate server and service context handles
rc = OCIHandleAlloc(envhp, (void**)&srvhp, OCI_HTYPE_SERVER, 0, NULL);
rc = OCIHandleAlloc(envhp, (void**)&svchp, OCI_HTYPE_SVCCTX, 0, NULL);
// Attach to the server
//rc = OCIServerAttach(srvhp, errhp, sid, strlen((char*)sid), 0);
// Set server in the service context
rc = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, (dvoid*)srvhp, 0, OCI_ATTR_SERVER, errhp);
// Allocate session handle
rc = OCIHandleAlloc(envhp, (void**)&authp, OCI_HTYPE_SESSION, 0, NULL);
// Set user name and password
rc = OCIAttrSet(authp, OCI_HTYPE_SESSION, (void*)user, strlen((char*)user),
OCI_ATTR_USERNAME, errhp);
rc = OCIAttrSet(authp, OCI_HTYPE_SESSION, (void*)pwd, strlen((char *)pwd),
OCI_ATTR_PASSWORD, errhp);
std::string path("oracle-server");
rc = OCIServerAttach(srvhp, errhp, (text *)path.c_str(), (sb4)path.length(), 0);
// Connect
rc = OCISessionBegin(svchp, errhp, authp, OCI_CRED_RDBMS, OCI_DEFAULT);
// Set session in the service context
rc = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, authp, 0, OCI_ATTR_SESSION, errhp);
// Allocate statement handle
rc = OCIHandleAlloc(envhp, (void**)&stmtp, OCI_HTYPE_STMT, 0, NULL);
// Prepare the query
rc = OCIStmtPrepare(stmtp, errhp, (text*)query, strlen(query), OCI_NTV_SYNTAX, OCI_DEFAULT);
char text[10];
int option=0;
// Define the select list items
rc = OCIDefineByPos(stmtp, &defnpp, errhp, 1, (void*)text, 5, SQLT_CHR, (void*)dataReceivedI,
dataReceived_len, dataReceived_code, OCI_DEFAULT);
if (rc != 0) {
OCIErrorGet(errhp, (ub4)1, NULL, &errcode, message, sizeof(message), (ub4)OCI_HTYPE_ERROR);
printf("%s", message);
}
rc = OCIDefineByPos(stmtp, &defnpp, errhp, 2, (void*)option, sizeof(int), SQLT_NUM, (void*)dataReceived_indI,
dataReceived_lenI, dataReceived_codeI, OCI_DEFAULT);
if (rc != 0) {
OCIErrorGet(errhp, (ub4)1, NULL, &errcode, message, sizeof(message), (ub4)OCI_HTYPE_ERROR);
printf("%s", message);
}
OCIBind* bindHandle2;
rc = OCIBindByPos(stmtp, &bindHandle2, errhp, 1,
(dvoid *)&option, (sword) sizeof(int), SQLT_NUM,
(dvoid *)0, (ub2 *)0, (ub2 *)0, (ub4)0, (ub4 *)0, OCI_DEFAULT);
if (rc != 0) {
OCIErrorGet(errhp, (ub4)1, NULL, &errcode, message, sizeof(message), (ub4)OCI_HTYPE_ERROR);
printf("%s", message);
}
strcpy_s(text, "test3");
option = 2;
rc = OCIStmtExecute(svchp, stmtp, errhp, 1, 0, 0,0, OCI_DEFAULT);
if (rc != 0) {
OCIErrorGet(errhp, (ub4)1, NULL, &errcode, message, sizeof(message), (ub4)OCI_HTYPE_ERROR);
printf("%s", message);
}
rc = OCIHandleFree(stmtp, OCI_HTYPE_STMT);
// Disconnect
rc = OCISessionEnd(svchp, errhp, authp, OCI_DEFAULT);
rc = OCIServerDetach(srvhp, errhp, OCI_DEFAULT);
rc = OCIHandleFree(envhp, OCI_HTYPE_ENV);
}
Can anyone see what I have done wrong?

Encoding H.264 Compression Session with CGDisplayStream

I'm trying to create an H.264 Compression Session with the data from my screen. I've created a CGDisplayStreamRef instance like so:
displayStream = CGDisplayStreamCreateWithDispatchQueue(0, 100, 100, k32BGRAPixelFormat, nil, self.screenCaptureQueue, ^(CGDisplayStreamFrameStatus status, uint64_t displayTime, IOSurfaceRef frameSurface, CGDisplayStreamUpdateRef updateRef) {
//Call encoding session here
});
Below is how I currently have the encoding function setup:
- (void) encode:(CMSampleBufferRef )sampleBuffer {
CVImageBufferRef imageBuffer = (CVImageBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer);
CMTime presentationTimeStamp = CMTimeMake(frameID++, 1000);
VTEncodeInfoFlags flags;
OSStatus statusCode = VTCompressionSessionEncodeFrame(EncodingSession,
imageBuffer,
presentationTimeStamp,
kCMTimeInvalid,
NULL, NULL, &flags);
if (statusCode != noErr) {
NSLog(#"H264: VTCompressionSessionEncodeFrame failed with %d", (int)statusCode);
VTCompressionSessionInvalidate(EncodingSession);
CFRelease(EncodingSession);
EncodingSession = NULL;
return;
}
NSLog(#"H264: VTCompressionSessionEncodeFrame Success");
}
I'm trying to understand how I can convert the data from my screen into a CMSampleBufferRef so I can properly call my encode function. So far, I've not been able to determine if this is possible, or the right approach for what I'm trying to do. Does anyone have any suggestions?
EDIT: I've gotten my IOSurfaceconverted to a CMBlockBuffer, but haven't yet figured out how to convert that to a CMSampleBufferRef:
void *mem = IOSurfaceGetBaseAddress(frameSurface);
size_t bytesPerRow = IOSurfaceGetBytesPerRow(frameSurface);
size_t height = IOSurfaceGetHeight(frameSurface);
size_t totalBytes = bytesPerRow * height;
CMBlockBufferRef blockBuffer;
CMBlockBufferCreateWithMemoryBlock(kCFAllocatorNull, mem, totalBytes, kCFAllocatorNull, NULL, 0, totalBytes, 0, &blockBuffer);
EDIT 2
Some more progress:
CMSampleBufferRef *sampleBuffer;
OSStatus sampleStatus = CMSampleBufferCreate(
NULL, blockBuffer, TRUE, NULL, NULL,
NULL, 1, 1, NULL,
0, NULL, sampleBuffer);
[self encode:*sampleBuffer];
Possibly, I'm a bit late but nevertheless, it could be helpful for others:
CGDisplayStreamCreateWithDispatchQueue(CGMainDisplayID(), 100, 100, k32BGRAPixelFormat, nil, self.screenCaptureQueue, ^(CGDisplayStreamFrameStatus status, uint64_t displayTime, IOSurfaceRef frameSurface, CGDisplayStreamUpdateRef updateRef) {
// The created pixel buffer retains the surface object.
CVPixelBufferRef pixelBuffer;
CVPixelBufferCreateWithIOSurface(NULL, frameSurface, NULL, &pixelBuffer);
// Create the video-type-specific description for the pixel buffer.
CMVideoFormatDescriptionRef videoFormatDescription;
CMVideoFormatDescriptionCreateForImageBuffer(NULL, pixelBuffer, &videoFormatDescription);
// All the necessary parts for creating a `CMSampleBuffer` are ready.
CMSampleBufferRef sampleBuffer;
CMSampleTimingInfo timingInfo;
CMSampleBufferCreateReadyWithImageBuffer(NULL, pixelBuffer, videoFormatDescription, &timingInfo, &sampleBuffer);
// Do the stuff
// Release the resources to let the frame surface be reused in the queue
// `kCGDisplayStreamQueueDepth` is responsible for the size of the queue
CFRelease(sampleBuffer);
CFRelease(pixelBuffer);
});

LDAP Authentication, ldap_sasl_bind_s not working but ldap_simple_bind_s works

I have a problem where in ldap_sasl_bind_s does not work, but ldap_simple_bind_s works.
The strange thing is, ldap_sasl_bind_s works even with wrong passwords and gives user the feeling that he has entered a correct password.
PFA code snippet of the problem and suggest me if anything is wrong with my approach.
{
int rc, aReturnVal = 0;
NSString *aUserDN = [NSString stringWithFormat:#"uid=%s,cn=users,dc=example,dc=com", username];
char* userDN = (char*)[aUserDN UTF8String];
rc = ldap_simple_bind_s (
ld,
userDN,
password
);
// TODO: ldap_simple_bind_s is a deprecated method and should not be used for long. ldap_sasl_bind_s is the right method, but is not working for now.
// Find the reason and get this code up and running.
// struct berval *servcred;
// struct berval cred;
// cred.bv_val = password; // my password
// cred.bv_len = strlen(password);
// rc = ldap_sasl_bind_s (
// ld,
// userDN,
// "DIGEST-MD5",
// &cred,
// NULL,
// NULL,
// &servcred
// );
if ( rc != LDAP_SUCCESS ) {
fprintf( stderr, "ldap_sasl_bind: %s\n", ldap_err2string( rc ) );
} else {
aReturnVal = 1;
}
return aReturnVal;
}
I have initialized the LDAP using following code SNIP:
rc = ldap_initialize(&ld, HOSTNAME);
version = LDAP_VERSION3;
ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, &version );
ldap_set_option( ld, LDAP_OPT_REFERRALS, 0 );
I need to be able to login with correct user name and when user tries to enter wrong user name, ldap should say so.
I have referred to following links and their related links to get to this conclusion:
LDAP - How to check a username/password combination?
How to do password authentication for a user using LDAP?
Digest-MD5 auth is more complicated than just sending a bind DN and password. You'll need to use ldap_sasl_interactive_bind_s and provide a callback so the SASL library can combine your credentials with the server-provided nonce.
This code (adapted from this blog post) works for me against an Active Directory server:
#include <stdio.h>
#include <stdlib.h>
#include <ldap.h>
#include <sasl/sasl.h>
typedef struct
{
char *username;
char *password;
} my_authdata;
int my_sasl_interact(LDAP *ld, unsigned flags, void *defaults, void *in)
{
my_authdata *auth = (my_authdata *)defaults;
sasl_interact_t *interact = (sasl_interact_t *)in;
if(ld == NULL) return LDAP_PARAM_ERROR;
while(interact->id != SASL_CB_LIST_END)
{
char *dflt = (char *)interact->defresult;
switch(interact->id)
{
case SASL_CB_GETREALM:
dflt = NULL;
break;
case SASL_CB_USER:
case SASL_CB_AUTHNAME:
dflt = auth->username;
break;
case SASL_CB_PASS:
dflt = auth->password;
break;
default:
printf("my_sasl_interact asked for unknown %ld\n",interact->id);
}
interact->result = (dflt && *dflt) ? dflt : (char *)"";
interact->len = strlen((char *)interact->result);
interact++;
}
return LDAP_SUCCESS;
}
int main(int argc, char *argv[])
{
if(argc < 3)
{
fprintf(stderr, "Usage: dmd5-bind [username] [password]\n");
return -1;
}
int rc;
LDAP *ld = NULL;
static my_authdata auth;
auth.username = argv[1];
auth.password = argv[2];
char *sasl_mech = ber_strdup("DIGEST-MD5");
char *ldapuri = ber_strdup("ldap://your.server.name.here");
int protocol = LDAP_VERSION3;
unsigned sasl_flags = LDAP_SASL_QUIET;
char *binddn = NULL;
rc = ldap_initialize(&ld, ldapuri);
if(rc != LDAP_SUCCESS)
{
fprintf(stderr, "ldap_initialize: %s\n", ldap_err2string(rc));
return rc;
}
if(ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &protocol) != LDAP_OPT_SUCCESS)
{
fprintf(stderr, "Could not set LDAP_OPT_PROTOCOL_VERSION %d\n", protocol);
return -1;
}
rc = ldap_sasl_interactive_bind_s(ld,
binddn,
sasl_mech,
NULL,
NULL,
sasl_flags,
my_sasl_interact,
&auth);
if(rc != LDAP_SUCCESS)
{
ldap_perror(ld, "ldap_sasl_interactive_bind_s");
ldap_unbind_ext_s(ld, NULL, NULL);
return rc;
}
fprintf(stdout, "Authentication succeeded\n");
rc = ldap_unbind_ext_s(ld, NULL, NULL);
sasl_done();
sasl_client_init(NULL);
return rc;
}

SecKeychainFindInternetPassword is not working

I have a problem with storing and reading from my keychain. First I tried to store use a char like this "account_name" in the Method SecKeychainFindInternetPassword for accountname and this runs. But now i would like to store a variable inside. But if i run this code the Programm cannot find the Keychain Item.
Please Help me.
(Sorry for my bad Englisch, i am a german student)
-(void)StorePasswordKeychain:(void*)password :(UInt32)passwordLength
{
char *userString;
userString = (char *)[_username UTF8String];
SecKeychainAddInternetPassword(
NULL,
StrLength("myserver.com"),
"myserver.com",
0,
NULL,
StrLength(userString),
userString,
0,
nil,
0,
kSecProtocolTypeHTTPS,
kSecAuthenticationTypeHTMLForm,
passwordLength,
password,
NULL
);
}
-(OSStatus)GetPasswordKeychain:(void *)passwordData :(UInt32 *)passwordLength
{
OSStatus status;
char *userString;
userString = (char *)[_username UTF8String];
status = SecKeychainFindInternetPassword(
NULL,
StrLength("myserver.com"),
"myserver.com",
0,
NULL,
StrLength(userString),
userString,
0,
nil,
0,
kSecProtocolTypeHTTPS,
kSecAuthenticationTypeHTMLForm,
passwordLength,
passwordData,
NULL
);
return status;
}
Two suggestions.. don't pass null into itemRef (the last arg). Then you'll have a pointer to the keychain you wish to modify.
Also, you should really check the error code to see if your add function worked.
OSStatus result = SecKeychainAddInternetPassword(
NULL,
StrLength("myserver.com"),
"myserver.com",
0,
NULL,
StrLength(userString),
userString,
0,
nil,
0,
kSecProtocolTypeHTTPS,
kSecAuthenticationTypeHTMLForm,
passwordLength,
password,
NULL
);
if(result != noErr){
NSLog(#"Error AddPassword result=:%d", result );
}
This is my sample program with the same code that you provided and it works fine.
int main(int argc, const char * argv[])
{
#autoreleasepool {
char *inputpassword = "topsecret";
UInt32 inputpassLength = strlen(inputpassword);
OSStatus status;
NSString *_username = #"account_name";
char *userString;
userString = (char *)[_username UTF8String];
status = SecKeychainAddInternetPassword(
NULL,
StrLength("myserver.com"),
"myserver.com",
0,
NULL,
StrLength(userString),
userString,
0,
nil,
0,
kSecProtocolTypeHTTPS,
kSecAuthenticationTypeHTMLForm,
inputpassLength,
inputpassword,
NULL
);
NSLog(#"Adding Status:%d", status);
UInt32 returnpasswordLength = 0;
char *passwordData;
status = SecKeychainFindInternetPassword(
NULL,
StrLength("myserver.com"),
"myserver.com",
0,
NULL,
StrLength(userString),
userString,
0,
nil,
0,
kSecProtocolTypeHTTPS,
kSecAuthenticationTypeHTMLForm,
&returnpasswordLength,
(void *)&passwordData,
NULL
);
NSLog(#"Retrieving status:%d", status);
NSLog(#"Password:%#", [[NSString alloc] initWithBytes:passwordData
length:returnpasswordLength
encoding:NSUTF8StringEncoding]);
}
return 0;
}