ldap ssl connection parameters in iOS - ios

I am trying to connect to ldaps server through through ldap_start_tls_s but i am continuously getting error -12(LDAP_INAPPROPRIATE_MATCHING).
Below is my code
const char*ldapServer=[#"ldaps://xx.xxx.xxx.xx" UTF8String];
LDAP *ld;
int rc;
/* Open LDAP Connection */
if( ldap_initialize( &ld, ldapServer ) )
{
perror( "ldap_initialize" );
}
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"server"
ofType:#"pem"];
NSString *newDir = [filePath stringByReplacingOccurrencesOfString:#"/server.pem" withString:#""];
int version = LDAP_VERSION3;
ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &version);
// ldap_set_option(ld, LDAP_OPT_X_TLS_CACERTFILE, [filePath UTF8String]);
// ldap_set_option(ld, LDAP_OPT_X_TLS_CERTFILE,NULL);
// ldap_set_option(ld, LDAP_OPT_X_TLS_KEYFILE, NULL);
// ldap_set_option(ld,LDAP_OPT_SSPI_FLAGS,0);
ldap_set_option(ld,LDAP_TIMELIMIT_EXCEEDED,[#"3000" UTF8String]);
ldap_set_option(ld,LDAP_OPT_REFERRALS,0);
ldap_set_option(NULL, LDAP_OPT_X_TLS_CTX, NULL);
ldap_set_option(NULL, LDAP_OPT_X_TLS_CACERTDIR,[newDir UTF8String]);
rc = ldap_start_tls_s(ld, NULL, NULL);
if( rc != LDAP_SUCCESS )
{
printf("start tls failed.\n");
}
I am stuck with this can any one help me to sort this out. Thanks in advance..

Related

Xcode app on iPhone6+ can't open file for binary read

I'm trying to open a file 'd.mp3' that I added to my Xcode 8.0 project.
If I double-click Xcode > project > 'd.mp3' the file plays just fine.
But, when Xcode runs my app on my iPhone6+ (iOS 10.0.1) then fopen() returns 0 for the file handle.
Code and output below...
bool read_next_chunk( char* relative_file_pathname, unsigned char* chunk_buffer, int chunk_size_bytes, FILE* file_handle )
{
const bool dbg = true;
// Get absolute file pathname:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *program_directory = [paths objectAtIndex:0];
NSString* absolute_pathname = [NSString stringWithFormat: #"%#/%s", program_directory, relative_file_pathname ];
if( dbg ) printf("\n%s: file '%s'. Path '%s'.", __FUNCTION__, relative_file_pathname, [absolute_pathname UTF8String] );
// Open file if not already open:
if( file_handle == NULL )
{
if( dbg ) printf("\n%s Open file %s.", __FUNCTION__, relative_file_pathname );
file_handle = fopen( [absolute_pathname UTF8String], "rb" ); // open for binary reading
if( dbg ) printf("\n%s file_handle %d.", __FUNCTION__, file_handle);
}
if( file_handle )
{
// Read next chunk of file into file_content_string:
int total_read_bytes = (int)fread( chunk_buffer, 1, chunk_size_bytes, file_handle );
if( total_read_bytes != chunk_size_bytes )
{
printf("\n %s: %d total_read_bytes != %d chunk_size_bytes -- FAULT!! <<<<<<<<<<<",__FUNCTION__, total_read_bytes, chunk_size_bytes);
return false;
}
return true;
}
else
{
printf("\ %s: Cannot open '%s' FAULT!! <<<<<<<<<<<", __FUNCTION__, relative_file_pathname );
return false;
}
}
read_next_chunk: file 'd.mp3'. Path '/var/mobile/Containers/Data/Application/C8B87C49-C6CF-4677-B775-6B3DF6EFD908/Documents/d.mp3'.
read_next_chunk Open file d.mp3.
read_next_chunk file_handle 0. read_next_chunk: Cannot open 'd.mp3' FAULT!! <<<<<<<<<<<
As rmaddy said, it is likely not in your documents directory. Try something like this:
NSString* filePath = [[NSBundle mainBundle] pathForResource:#"d" ofType:#"mp3"];

Data are not inserting into sqliteDB iOS

I have created a table(REPORTDATA) in existing database. I am trying to insert the values in to table. But it is not inserted. I am using the following code.
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
databasePath = [docsDir stringByAppendingPathComponent:#"Album.db"];
const char *dbpath = [databasePath UTF8String];
NSString *insertSQL;
if (sqlite3_open(dbpath, & albumDB) == SQLITE_OK)
{
int rowCount = [self GetArticlesCount];
rowCount += 1;
NSString *tempcount = [NSString stringWithFormat:#"%d", rowCount];
insertSQL = [NSString stringWithFormat: #"INSERT INTO REPORTDATA (Num, Json) VALUES ('%#','%#')", tempcount, tempcount];
char *errmsg=nil;
if(sqlite3_exec(albumDB, [insertSQL UTF8String], NULL, NULL, &errmsg)==SQLITE_OK)
{
}
else
{
NSLog(#"Error Message is =%s",errmsg);
}
}
sqlite3_close(albumDB);
Get number of rows in a table:
- (int) GetArticlesCount
{
int count = 0;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = dirPaths[0];
databasePath = [docsDir stringByAppendingPathComponent:#"Album.db"];
if (sqlite3_open([self.databasePath UTF8String], &albumDB) == SQLITE_OK)
{
const char* sqlStatement = "SELECT COUNT(*) FROM REPORTDATA";
sqlite3_stmt *statement;
if( sqlite3_prepare_v2(albumDB, sqlStatement, -1, &statement, NULL) == SQLITE_OK )
{
//Loop through all the returned rows (should be just one)
while( sqlite3_step(statement) == SQLITE_ROW )
{
count = sqlite3_column_int(statement, 0);
}
}
else
{
NSLog( #"Failed from sqlite3_prepare_v2. Error is: %s", sqlite3_errmsg(albumDB) );
}
sqlite3_finalize(statement);
sqlite3_close(albumDB);
}
return count;
}
I am getting
Error Message is =(null).
I'd suggest examining the actual return value of sqlite3_exec:
int rc;
char *errmsg = NULL;
if ((rc = sqlite3_exec(albumDB, [insertSQL UTF8String], NULL, NULL, &errmsg)) == SQLITE_OK) {
NSLog(#"Insert succeeded");
} else {
NSLog(#"Insert failed: %s (%ld)", errmsg, (long)rc);
if (errmsg) sqlite3_free(errmsg);
}
You report that it returned 21, which is SQLITE_MISUSE. This is typical if you called the API functions in the wrong order (e.g. performing some SQL after the database was closed).
The GetArticlesCount method is reopening a database (which is already open), replacing the albumDB variable with a new sqlite3 * pointer. Then, GetArticlesCount is closing the database, and when you return to the first method, the albumDB pointer is now referencing a closed database handle. Thus subsequent SQL calls will generate SQLITE_MISUSE.
To avoid this problem, I would advise against having each function that performs SQL from opening and closing the database. Open the database once and then have all subsequent SQLite calls use that one sqlite3 * pointer.
Try to find error by using below code.
const char *sql = "INSERT INTO REPORTDATA (Num, Json) VALUES VALUES (?,?)"
if (sqlite3_prepare_v2(albumDB, sql, -1, &statement, NULL) != SQLITE_OK)
{
NSLog(#"Prepare failure: %s", sqlite3_errmsg(albumDB));
}
if (sqlite3_bind_text(statement, 1, [commentString UTF8String], -1, NULL) != SQLITE_OK)
{
NSLog(#"Bind 1 failure: %s", sqlite3_errmsg(albumDB));
}
if (sqlite3_step(statement) != SQLITE_DONE) {
NSLog(#"Step failure: %s", sqlite3_errmsg(albumDB));
}
sqlite3_finalize(statement);
As others suggested, I also recommend you to examine the actual error message.
9 of 10, I believe it is because the database file Album.db is not in the documents directory.
Try adding a breakpoint and check the databasePath value, open that directory and confirm the file is there.
If the file has 0 bytes of size, make sure to remove it and add the correct file to your Bundle Resources in:
Project -> Targets -> right target -> Build Phases -> Copy Bundle Resources
EDIT: In your case, you closed the database in GetArticlesCount and tried to use the database pointer after closing it. So I believe Rob's answer is the right solution.

SSL Certificate Details in UIWebView

I need to show SSL certificate details of displayed URL in a UIWebView something like Google's Chrome browser shows:
How to obtain this data from UIWebView.
We are intercepting the call at the network level (rather than the UIWebView), and using [NSURLConnectionDelegate connection:willSendRequestForAuthenticationChallenge:]. This gives you a NSURLAuthenticationChallenge instance, and if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust then NSURLAuthenticationChallenge.protectionSpace.serverTrust is a SecTrustRef.
Given the SecTrustRef, you can follow SecCertificateRef: How to get the certificate information? and do something like this:
#import <Security/Security.h>
#import <openssl/x509.h>
X509* X509CertificateFromSecTrust(SecTrustRef trust) {
SecCertificateRef cert = SecTrustGetCertificateAtIndex(trust, 0);
CFDataRef certDataRef = SecCertificateCopyData(cert);
NSData *certData = (__bridge NSData *)certDataRef;
const void* certDataBytes = certData.bytes;
X509* result = d2i_X509(NULL, (const unsigned char**)&certDataBytes, certData.length);
CFRelease(certDataRef);
return result;
}
static NSString* X509NameField(X509_NAME* name, char* key) {
if (name == NULL)
return nil;
int nid = OBJ_txt2nid(key);
int index = X509_NAME_get_index_by_NID(name, nid, -1);
X509_NAME_ENTRY *nameEntry = X509_NAME_get_entry(name, index);
if (nameEntry == NULL)
return nil;
ASN1_STRING *nameASN1 = X509_NAME_ENTRY_get_data(nameEntry);
if (nameASN1 == NULL)
return nil;
unsigned char *issuerName = ASN1_STRING_data(nameASN1);
return [NSString stringWithUTF8String:(char *)issuerName];
}
NSString* X509CertificateGetSubjectCommonName(X509* cert) {
if (cert == NULL)
return nil;
X509_NAME *subjectName = X509_get_subject_name(cert);
return X509NameField(subjectName, "CN"); // Common name.
}
NSString* X509CertificateGetIssuerName(X509* certX509) {
if (certX509 == NULL)
return nil;
X509_NAME *issuerX509Name = X509_get_issuer_name(certX509);
if (issuerX509Name == NULL)
return nil;
return X509NameField(issuerX509Name, "O"); // organization
}
This is not a simple piece of work. You'll need to understand OpenSSL's X509 code, the Security framework, and whatever you're doing at the network layer for SSL trust checks. There might be other ways that you can get hold of a SecTrustRef or SecCertificateRef, but I'm not using them if there are.

OpenAL with 64bit architecture on iPhone

When I run my previous game against the 64 bit architecture, I get OpenAL errors..
It says "no matching function for call to alGenBuffers" and "no matching function for call to alGenSources". How can I fix these errors?
The whole method
-(bool) loadSoundWithKey:(NSString *)_soundKey File:(NSString *)_file Ext:(NSString *) _ext Loop:(bool)loops{
ALvoid * outData;
ALenum error = AL_NO_ERROR;
ALenum format;
ALsizei size;
ALsizei freq;
NSBundle * bundle = [NSBundle mainBundle];
CFURLRef fileURL = (__bridge_retained CFURLRef)[NSURL fileURLWithPath:[bundle pathForResource:_file ofType:_ext]];
if (!fileURL)
{
NSLog(#"file not found.");
return false;
}
outData = GameGetOpenALAudioData(fileURL, &size, &format, &freq);
CFRelease(fileURL);
if((error = alGetError()) != AL_NO_ERROR) {
printf("error loading sound: %xn", error);
exit(1);
}
NSUInteger bufferID;
alGenBuffers(1, &bufferID); // error
alBufferData(bufferID,format,outData,size,freq);
[bufferStorageArray addObject:[NSNumber numberWithUnsignedInteger:bufferID]];
NSUInteger sourceID;
alGenSources(1, &sourceID); // error
alSourcei(sourceID, AL_BUFFER, bufferID);
alSourcef(sourceID, AL_PITCH, 1.0f);
alSourcef(sourceID, AL_GAIN, 1.0f);
if (loops) alSourcei(sourceID, AL_LOOPING, AL_TRUE);
if (outData)
{
free(outData);
outData = NULL;
}
return true;
}
I have figured out..
Apparently alGenBuffers and alGenSources require GLuint not NSUInteger!

Issue with digital signature generated using Podofo library

I'm using OpenSSL to generate digital signature for a PDF by PoDoFo library.
Here is the logic for signature handler
OpenSSLSignatureHandler.h
#import <Foundation/Foundation.h>
// OpenSSL includes
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pkcs12.h>
#include <openssl/pkcs7.h>
#include <openssl/rsa.h>
#include <openssl/sha.h>
#interface OpenSSLSignatureHandler : NSObject
{
SHA_CTX m_sha_ctx;
EVP_PKEY* mp_pkey; // private key
X509* mp_x509; // signing certificate
STACK_OF(X509)* mp_ca; // certificate chain up to the CA
}
- (id) initWithCert:(NSString*) p12file password: (NSString*) password;
- (void) AppendData: (NSData*)data;
- (NSData*) getSignature;
#end
OpenSSLSignatureHandler.m
#import "OpenSSLSignatureHandler.h"
#include <string>
#implementation OpenSSLSignatureHandler
- (id) initWithCert:(NSString*) p12file password: (NSString*) password{
if (self = [super init]) {
// Initialize OpenSSL library
CRYPTO_malloc_init();
ERR_load_crypto_strings();
OpenSSL_add_all_algorithms();
FILE* fp = fopen([p12file cStringUsingEncoding: NSASCIIStringEncoding], "rb");
if (fp == NULL)
#throw ([NSException exceptionWithName: #"PDFNet Exception" reason: #"Cannot open private key." userInfo: nil]);
PKCS12* p12 = d2i_PKCS12_fp(fp, NULL);
fclose(fp);
if (p12 == NULL)
#throw ([NSException exceptionWithName: #"PDFNet Exception" reason: #"Cannot parse private key." userInfo: nil]);
mp_pkey = NULL;
mp_x509 = NULL;
mp_ca = NULL;
int parseResult = PKCS12_parse(p12, [password cStringUsingEncoding: NSASCIIStringEncoding], &mp_pkey, &mp_x509, &mp_ca);
PKCS12_free(p12);
if (parseResult == 0)
#throw ([NSException exceptionWithName: #"PDFNet Exception" reason: #"Cannot parse private key." userInfo: nil]);
//initialize sha context
SHA1_Init(&m_sha_ctx);
}
return self;
}
- (void) AppendData: (NSData*)data
{
SHA1_Update(&m_sha_ctx, [data bytes], [data length]);
return;
}
- (BOOL) Reset
{
SHA1_Init(&m_sha_ctx);
return (YES);
}
- (NSData*) getSignature
{
unsigned char sha_buffer[SHA_DIGEST_LENGTH];
memset((void*) sha_buffer, 0, SHA_DIGEST_LENGTH);
SHA1_Final(sha_buffer, &m_sha_ctx);
PKCS7* p7 = PKCS7_new();
PKCS7_set_type(p7, NID_pkcs7_signed);
PKCS7_SIGNER_INFO* p7Si = PKCS7_add_signature(p7, mp_x509, mp_pkey, EVP_sha1());
PKCS7_add_attrib_content_type(p7Si, OBJ_nid2obj(NID_pkcs7_data));
PKCS7_add0_attrib_signing_time(p7Si, NULL);
PKCS7_add1_attrib_digest(p7Si, (const unsigned char*) sha_buffer, SHA_DIGEST_LENGTH);
PKCS7_add_certificate(p7, mp_x509);
int c = 0;
for ( ; c < sk_X509_num(mp_ca); c++) {
X509* cert = sk_X509_value(mp_ca, c);
PKCS7_add_certificate(p7, cert);
}
PKCS7_set_detached(p7, 1);
PKCS7_content_new(p7, NID_pkcs7_data);
PKCS7_SIGNER_INFO_sign(p7Si);
int p7Len = i2d_PKCS7(p7, NULL);
NSMutableData* signature = [NSMutableData data];
unsigned char* p7Buf = (unsigned char*) malloc(p7Len);
if (p7Buf != NULL) {
unsigned char* pP7Buf = p7Buf;
i2d_PKCS7(p7, &pP7Buf);
[signature appendBytes: (const void*) p7Buf length: p7Len];
free(p7Buf);
}
PKCS7_free(p7);
return (signature);
}
- (void) dealloc
{
sk_X509_free(mp_ca);
X509_free(mp_x509);
EVP_PKEY_free(mp_pkey);
// Release OpenSSL resource usage
ERR_free_strings();
EVP_cleanup();
[super dealloc];
}
#end
Using podofo to embed signature
void CreateSimpleForm( PoDoFo::PdfPage* pPage, PoDoFo::PdfStreamedDocument* pDoc, const PoDoFo::PdfData &signatureData )
{
PoDoFo::PdfPainter painter;
PoDoFo::PdfFont* pFont = pDoc->CreateFont( "Courier" );
painter.SetPage( pPage );
painter.SetFont( pFont );
painter.DrawText( 10000 * CONVERSION_CONSTANT, 280000 * CONVERSION_CONSTANT, "PoDoFo Sign Test" );
painter.FinishPage();
PoDoFo::PdfSignatureField signField( pPage, PoDoFo::PdfRect( 0, 0, 0, 0 ), pDoc );
signField.SetFieldName("SignatureFieldName");
signField.SetSignature(signatureData);
signField.SetSignatureReason("Document verification");
// Set time of signing
signField.SetSignatureDate( PoDoFo::PdfDate() );
}
+(void)addDigitalSignatureOnPage:(NSInteger)pageIndex outpath:(NSString*)path/*doc:(PoDoFo::PdfMemDocument*)aDoc*/{
PoDoFo::PdfPage* pPage;
PoDoFo::PdfSignOutputDevice signer([path UTF8String]);
// Reserve space for signature
signer.SetSignatureSize(1024);
if([[NSFileManager defaultManager] fileExistsAtPath:path]){
PoDoFo::PdfStreamedDocument writer( &signer, PoDoFo::ePdfVersion_1_5 );
// Disable default appearance
writer.GetAcroForm(PoDoFo::ePdfCreateObject, PoDoFo::PdfAcroForm::ePdfAcroFormDefaultAppearance_None);
pPage = writer.CreatePage(PoDoFo::PdfPage::CreateStandardPageSize(PoDoFo::ePdfPageSize_A4 ) );
TEST_SAFE_OP( CreateSimpleForm( pPage, &writer, *signer.GetSignatureBeacon() ) );
TEST_SAFE_OP( writer.Close() );
}
// Check if position of signature was found
if(signer.HasSignaturePosition()) {
// Adjust ByteRange for signature
signer.AdjustByteRange();
// Read data for signature and count it
// We have to seek at the beginning of the file
signer.Seek(0);
//OpenSSLSignatureHandler
NSString * p12certpath = [[NSBundle mainBundle] pathForResource:#"iphone-cert" ofType:#"p12"];
OpenSSLSignatureHandler*signatureHandler = [[OpenSSLSignatureHandler alloc] initWithCert:p12certpath password:#"test123$"];
char buff[65536];
size_t len;
while( (len = signer.ReadForSignature(buff, 65536))>0 )
{
NSData* data = [NSData dataWithBytes:(const void *)buff length:len];
[signatureHandler AppendData:data];
}
const PoDoFo::PdfData *pSignature = NULL;
// NSString *pkcsMessage = [[signatureHandler getSignature] base64EncodedString];
// NSLog(#"OpenSSLSignatureHandler signature message = %#",pkcsMessage);
// const char * cstr = [pkcsMessage UTF8String];
// if(pSignature==NULL)pSignature = new PoDoFo::PdfData(cstr, sizeof(cstr));
unsigned char *bytePtr = (unsigned char *)[[signatureHandler getSignature] bytes];
std::string str;
str.append(reinterpret_cast<const char*>(bytePtr));
// Paste signature to the file
if(pSignature==NULL)pSignature = new PoDoFo::PdfData(str.c_str(), sizeof(str));
NSLog(#"str = %s",str.c_str());
NSLog(#"sizeof(str) = %lu",sizeof(str));
signer.SetSignature(*pSignature);
}
signer.Flush();
}
But the signature that's embeded in the PDF is always empty
can some help with this issue ?

Resources