Conflicting types for 'SecRandomCopyBytes' - ios

I get an error on xCode when I'm trying to archive a new version of my app and I can't figurate out where it come from and how can I fix it.
Look at the printscreen from xcode: Screenshot

iOS 11 changed the signature of that method.
You can try this
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000
extern int SecRandomCopyBytes(SecRandomRef rnd, size_t count, void *bytes) __attribute__((weak_import));
#else
extern int SecRandomCopyBytes(SecRandomRef rnd, size_t count, uint8_t *bytes) __attribute__((weak_import));
#endif
Source : https://github.com/RNCryptor/RNCryptor/issues/248

This worked for me on macOS
replacing with
extern int SecRandomCopyBytes(SecRandomRef rnd, size_t count, void * bytes) __attribute__((weak_import));

Related

How to implement PT_DENY_ATTACH (anti-debugging in iOS )

PT_DENY_ATTACH is an anti-debugging feature that helps prevent debuggers from attaching to the app. Following code can be implemented in main() to prevent GDB from attaching to the application. :
#import <dlfcn.h>
#import <sys/types.h>
typedef int (*ptrace_ptr_t)(int _request, pid_t _pid, caddr_t _addr, int _data);
#define PT_DENY_ATTACH 31
void disable_gdb() {
void* handle = dlopen(0, RTLD_GLOBAL | RTLD_NOW);
ptrace_ptr_t ptrace_ptr = dlsym(handle, "ptrace");
ptrace_ptr(PT_DENY_ATTACH, 0, 0, 0);
dlclose(handle);
}
int main(int argc, char *argv[]) {
#autoreleasepool {
#ifdef DEBUG
//do nothing
#else
disable_gdb();
#endif
}}
Guys it is true that this trick has been worked around and can be bypassed by overriding but have a look at that
Here the guys from iphonedevwiki.net are showing another way to implement the same thing in assembly, making it much harder to be patched. So to bypass this assembly implementation one has to have the Mach-O binary decrypted and override the implementation of the function, for example an attacker could swap all assembly instructions from the function with only nop instructions which do nothing. But if you obfuscate your assembly routine, it will be much harder for attacker to recognise what is happening, so only the most experienced folks will be able bypass that.
For those of you who don't know how to write assembly in Swift 5 project, here is what you will need to do:
Create a new C File + Header
lets name them disable_debuggers_advanced.c and disable_debuggers_advanced.h
In disable_debuggers_advanced.c add the following:
#include "disable_debug_advanced.h"
void mRiYXNnZnZmZGF2Ym() {
// No Need to encode these strings, because they will be directly compiled, they are not going to be present in the 'DATA' segment of the binary.
__asm (
"mov r0, #31\n" // set #define PT_DENY_ATTACH (31) to r0
"mov r1, #0\n" // clear r1
"mov r2, #0\n" // clear r2
"mov r3, #0\n" // clear r3
"mov ip, #26\n" // set the instruction pointer to syscal 26
"svc #0x80\n" // SVC (formerly SWI) generates a supervisor call. Supervisor calls are normally used to request privileged operations or access to system resources from an operating system
);
}
In disable_debuggers_advanced.h add the following:
#ifndef disable_debug_advanced_h
#define disable_debug_advanced_h
#include <stdio.h>
/**
Original name: `disable_gdb_advanced()`
This function makes the process deny the attaching request by debugers by
simulating what is already available on macOS:
ptrace(PT_DENY_ATTACH, 0, 0, 0);
by implementing it directly in assembly language.
This method of disabling debugers is well known to attackers but there is nothing they can do to easily bypass it
because it is a part of the kernel memory space.
Please note that this will make XCode not being able to attach its debuger to the process too,
so run it only in release builds.
source: https://iphonedevwiki.net/index.php/Crack_prevention#PT_DENY_ATTACH
*/
void mRiYXNnZnZmZGF2Ym(void) __attribute__((always_inline));
#endif /* disable_debug_advanced_h */
Add #include "disable_debug_advanced.h" to your bridging header and a bridging header if your project does not already have one.
Now you can call this function to disable debuggers.
Note that this will break even the XCode debugger, so use it only on release builds
If you are wondering about the __attribute__((always_inline)) part and the weird name it is because we want our function to be hidden as much as possible. If you are not familiar with function inlining, you can watch my video about function inlining here where i describe it in depth or you can read in wikipedia about it. Even thought it is a speed compiler optimisation, it could give us benefits here because if you call it from multiple locations it will be harder for attacker to patch all function body copies in the app.
And the name is written like this, because this inlining is just a hint to the compiler, it is not guaranteed that it will happen. And if it does not happen and our function for disabling the debugger is clearly defined in the TEXT segment of our binary, we want it to be at least with obfuscated name, so that no one could guess what it does just by reading its assembly label.
In my opinion one should call this as a top level function even before the UIApplication object is created.
In order to do that:
Add a new file to your Swift project and name it 'main.swift' (NAME IS IMPORTANT)
Remove the #UIApplicationMain tag from your AppDelegates class definition.
In your main.swift file write the following:
mRiYXNnZnZmZGF2Ym() // disable debuggers
// initialises the UIApplication and fires the event loop.
// This function never returns!
UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(AppDelegate.self))
If you want to see a video of how to execute top level code in main.swift, you can see me doing it on this video
In attempt to make it even more obfuscated and harder to crack, one could use assembly obfuscators like this one Movfuscator so that only a few people would be able to recognise what these assembly instructions mean.
Note: according to the wiki page of this tool, it has been workearound and must not be used:
IMPORTANT NOTE: This trick has been worked around by pirates. Don't rely on it!
Assuming you are referring to a Hybrid application created in MobileFirst Studio 7.1 - this, well, is not different than any other iOS app.
The end result of a Hybrid app, is still an Xcode project that you open in Xcode in order to build the application. This means then that you need to place your code in the same place in the Xcode project as if this was a regular Xcode project (which, it is), per the wiki page for PT_DENY_ATTACH.
As noted by #Idan Adar - this trick is workedAround, but in case u want to try it in any education or some other purpose u can try do following:
add define for u'r app to allow u run and debug if needed
#define SOME
add following code in main.m
#define SOME
#import <UIKit/UIKit.h>
#import "AppDelegate.h"
#ifdef SOME
#import <dlfcn.h>
#import <sys/types.h>
typedef int (*ptrace_ptr_t)(int request, pid_t pid, caddr_t addr, int data);
#if !defined(PT_DENY_ATTACH)
#define PT_DENY_ATTACH 31
#endif // !defined(PT_DENY_ATTACH)
void disable_gdb();
int main(int argc, char *argv[])
{
// disable_gdb();
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
void disable_gdb()
{
void* handle = dlopen(0, RTLD_GLOBAL | RTLD_NOW);
ptrace_ptr_t ptrace_ptr = dlsym(handle, "ptrace");
ptrace_ptr(PT_DENY_ATTACH, 0, 0, 0);
dlclose(handle);
}
int main3(int argc, char *argv[])
{
return -1;
}
#else
int main(int argc, char *argv[])
{
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
#endif
Here - some good points to start about
I saw this question has not marked correct answered yet. I already use below code block to use anti-debugging. Please open your main.m file to added below code snipped.
#import "AppDelegate.h"
#import "Application.h"
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/sysctl.h>
#include <stdlib.h>
typedef int (*PYStdWriter)(void *, const char *, int);
static PYStdWriter _oldStdWrite;
#define PT_DENY_ATTACH 31
int __pyStderrWrite(void *inFD, const char *buffer, int size)
{
if ( strncmp(buffer, "AssertMacros:", 13) == 0 ) {
return 0;
}
return _oldStdWrite(inFD, buffer, size);
}
static int is_debugger_present(void)
{
int name[4];
struct kinfo_proc info;
size_t info_size = sizeof(info);
info.kp_proc.p_flag = 0;
name[0] = CTL_KERN;
name[1] = KERN_PROC;
name[2] = KERN_PROC_PID;
name[3] = getpid();
if (sysctl(name, 4, &info, &info_size, NULL, 0) == -1) {
perror("sysctl");
exit(-1);
}
return ((info.kp_proc.p_flag & P_TRACED) != 0);
}
int main(int argc, char *argv[]) {
#ifdef DEBUG
_oldStdWrite = stderr->_write;
stderr->_write = __pyStderrWrite;
#autoreleasepool {
return UIApplicationMain(argc, argv, NSStringFromClass([Application class]), NSStringFromClass([AppDelegate class]));
}
#else
//Anti Debugging Code
//https://coredump.gr/articles/ios-anti-debugging-protections-part-2/
//ptrace(PT_DENY_ATTACH, 0, 0, 0);
printf("Looping forever");
fflush(stdout);
while (1)
{
sleep(1);
if (is_debugger_present())
{
//[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"isAntiDebug"];
printf("Debugger detected! Terminating...\n");
return -1;
}
printf(".");
fflush(stdout);
_oldStdWrite = stderr->_write;
stderr->_write = __pyStderrWrite;
#autoreleasepool {
//[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"isAntiDebug"];
int retVal = UIApplicationMain(argc, argv, NSStringFromClass([Application class]), NSStringFromClass([AppDelegate class]));
return retVal;
}
}
#endif
}
As pointed out by Stoyan. Your implementation could be easily bypassed. You should add an assembly code. Just one missing thing from the above answer is that you have to add arm64 macro or you will not be able to build your project on simulators (OS X are using x86_64 arch)
So add this:
#if defined (__arm64__)
__asm(
"mov x0, #26\n" // ptrace
"mov x1, #31\n" // PT_DENY_ATTACH
"mov x2, #0\n"
"mov x3, #0\n"
"mov x16, #0\n"
"svc #128\n"
);
I wrote a simple guide for this. Check it out

Xcode extern error

I have problem with Xcode, I am getting following error when running the code:
Error : Expected identifier or ')'
Here is th code:
#import "IOKitLib.h"
#import <dlfcn.h>
#import <pthread.h>
#import <mach/mach.h>
#import <sys/ptrace.h>
#import <libkern/OSAtomic.h>
static mach_port_t masterPort = 0;
extern "C" kern_return_t io_service_open_extended
(
mach_port_t service,
task_t owningTask,
uint32_t connect_type,
NDR_record_t ndr,
io_buf_ptr_t properties,
mach_msg_type_number_t propertiesCnt,
kern_return_t *result,
mach_port_t *connection
);
Please help me to solve this problem and let me know where am I doing wrong. Thanks !
extern "C" is valid in C++ only. You can make the declaration usable in any language (C++, C or Objective-C), from a header file for example, using the __cplusplus guard macro:
#ifdef __cplusplus
extern "C" {
#endif
kern_return_t io_service_open_extended
(
mach_port_t service,
task_t owningTask,
uint32_t connect_type,
NDR_record_t ndr,
io_buf_ptr_t properties,
mach_msg_type_number_t propertiesCnt,
kern_return_t *result,
mach_port_t *connection
);
#ifdef __cplusplus
}
#endif

byte array in arduino library

ok so here is one for you maybe simple but i am not so sure.
i have the following code and it may be clear what i wish to do by looking at the code.
Arduino.ino
RF myRF; //Creation of RF class.
const int dataSize = 500;
byte storedData[dataSize];
//array is populated through program then the following is called
myRF.populate(storedData);
RF.CCP
const int dataSize = 500;
byte recivedData[dataSize];
void RF::populate(byte reciveddata){
recivedData = reciveddata;
}
RF.H
#include Arduino.h
#ifndef RF_H
#define RF_H
class RF {
public:
RF();
~RF();
void recive();
void send();
void print();
void sendnew(byte Storeddata);
};
#endif
this is however producing an error "byte is not declared"
Hope its clear what i intend to do and hope you can help thanks.
There are two problems in your files:
h file:
#include Arduino.h
You should write
#include <Arduino.h>
c file:
const int dataSize = 500;
byte recivedData[dataSize];
void RF::populate(byte reciveddata){
recivedData = reciveddata;
}
Here you have a big problem. You are declaring recivedData here, but you want to assign it a value coming from another part of the program. This is not how it works.
IMO you have two ways to do this.
1) store just the pointer to the memory; this way is faster and occupies less memory than solution 2, but you have to ensure that the storedData variable you pass in the .ino file is not changed during the function
#include "RF.h" // I hope you already included this
byte *recivedData;
void RF::populate(byte *reciveddata){
recivedData = reciveddata;
}
2) copy the content of the received array to this array; this way you have a copy of the array, so you occupy twice the memory (but you can edit storedData without problems).
#include "RF.h" // I hope you already included this
const int dataSize = 500;
byte recivedData[dataSize];
int recivedDataLength;
void RF::populate(byte *reciveddata, int reciveddatalength){
recivedDataLength = (reciveddatalength>dataSize) ? dataSize : reciveddatalength;
for (int i = 0; i < recivedDataLength; i++)
recivedData[i] = reciveddata[i];
}

Get CellID, MCC, MNC, LAC, and Network in iOS 5.1

I need to retrieve CellID, MCC, MNC, LAC and Network (GSM, 3G) of the current Serving Cell Tower in iOS 5.1 (iPhone 4S). I know this information is available because I can see it in FieldTest Mode (accessible after calling ****3001#12345#****). I suppose it to be accessible via Private/Undocumented iOS Frameworks.
In the question iphone, check values of cellId / Lac the author indicates I can get radio Informations cellId, Lac, MNC, MCC on iOS, but no information on how to do this is provided.
Can anybody tell me how to get this info?
I know three ways on how you can do it on iOS 5.x - 7.x. All of them use private APIs from CoreTelephony.framework. Supports both GSM and UMTS.
1) Using cell monitor
struct CTResult
{
int flag;
int a;
};
extern CFStringRef const kCTCellMonitorCellType;
extern CFStringRef const kCTCellMonitorCellTypeServing;
extern CFStringRef const kCTCellMonitorCellTypeNeighbor;
extern CFStringRef const kCTCellMonitorCellId;
extern CFStringRef const kCTCellMonitorLAC;
extern CFStringRef const kCTCellMonitorMCC;
extern CFStringRef const kCTCellMonitorMNC;
extern CFStringRef const kCTCellMonitorUpdateNotification;
id _CTServerConnectionCreate(CFAllocatorRef, void*, int*);
void _CTServerConnectionAddToRunLoop(id, CFRunLoopRef, CFStringRef);
#ifdef __LP64__
void _CTServerConnectionRegisterForNotification(id, CFStringRef);
void _CTServerConnectionCellMonitorStart(id);
void _CTServerConnectionCellMonitorStop(id);
void _CTServerConnectionCellMonitorCopyCellInfo(id, void*, CFArrayRef*);
#else
void _CTServerConnectionRegisterForNotification(struct CTResult*, id, CFStringRef);
#define _CTServerConnectionRegisterForNotification(connection, notification) { struct CTResult res; _CTServerConnectionRegisterForNotification(&res, connection, notification); }
void _CTServerConnectionCellMonitorStart(struct CTResult*, id);
#define _CTServerConnectionCellMonitorStart(connection) { struct CTResult res; _CTServerConnectionCellMonitorStart(&res, connection); }
void _CTServerConnectionCellMonitorStop(struct CTResult*, id);
#define _CTServerConnectionCellMonitorStop(connection) { struct CTResult res; _CTServerConnectionCellMonitorStop(&res, connection); }
void _CTServerConnectionCellMonitorCopyCellInfo(struct CTResult*, id, void*, CFArrayRef*);
#define _CTServerConnectionCellMonitorCopyCellInfo(connection, tmp, cells) { struct CTResult res; _CTServerConnectionCellMonitorCopyCellInfo(&res, connection, tmp, cells); }
#endif
...
id CTConnection = _CTServerConnectionCreate(NULL, CellMonitorCallback, NULL);
_CTServerConnectionAddToRunLoop(CTConnection, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
_CTServerConnectionRegisterForNotification(CTConnection, kCTCellMonitorUpdateNotification);
_CTServerConnectionCellMonitorStart(CTConnection);
int CellMonitorCallback(id connection, CFStringRef string, CFDictionaryRef dictionary, void *data)
{
int tmp = 0;
CFArrayRef cells = NULL;
_CTServerConnectionCellMonitorCopyCellInfo(connection, (void*)&tmp, &cells);
if (cells == NULL)
{
return 0;
}
for (NSDictionary* cell in (NSArray*)cells)
{
int LAC, CID, MCC, MNC;
if ([cell[(NSString*)kCTCellMonitorCellType] isEqualToString:(NSString*)kCTCellMonitorCellTypeServing])
{
LAC = [cell[(NSString*)kCTCellMonitorLAC] intValue];
CID = [cell[(NSString*)kCTCellMonitorCellId] intValue];
MCC = [cell[(NSString*)kCTCellMonitorMCC] intValue];
MNC = [cell[(NSString*)kCTCellMonitorMNC] intValue];
}
else if ([cell[(NSString*)kCTCellMonitorCellType] isEqualToString:(NSString*)kCTCellMonitorCellTypeNeighbor])
{
}
}
CFRelease(cells);
return 0;
}
2) Using CTTelephonyCenter
kCTRegistrationCellChangedNotification is sent every time current serving cell tower is changed.
extern CFStringRef const kCTRegistrationCellChangedNotification;
extern CFStringRef const kCTRegistrationGsmLac;
extern CFStringRef const kCTRegistrationLac;
extern CFStringRef const kCTRegistrationGsmCellId;
extern CFStringRef const kCTRegistrationCellId;
CFStringRef CTSIMSupportCopyMobileSubscriberCountryCode(CFAllocatorRef);
CFStringRef CTSIMSupportCopyMobileSubscriberNetworkCode(CFAllocatorRef);
id CTTelephonyCenterGetDefault();
void CTTelephonyCenterAddObserver(id, void, CFNotificationCallback, CFStringRef, void, CFNotificationSuspensionBehavior);
...
CTTelephonyCenterAddObserver(CTTelephonyCenterGetDefault(), NULL, callback, NULL, NULL, CFNotificationSuspensionBehaviorHold);
void callback(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo)
{
NSString* notification = (NSString*)name;
NSDictionary *cellInfo = (NSDictionary*)userInfo;
if ([notification isEqualToString:(NSString*)kCTRegistrationCellChangedNotification])
{
int LAC, CID, MCC, MNC;
if (cellInfo[(NSString*)kCTRegistrationGsmLac])
{
LAC = [cellInfo[(NSString*)kCTRegistrationGsmLac] intValue];
}
else if (data[(NSString*)kCTRegistrationLac])
{
LAC = [cellInfo[(NSString*)kCTRegistrationLac] intValue];
}
if (cellInfo[(NSString*)kCTRegistrationGsmCellId])
{
CID = [cellInfo[(NSString*)kCTRegistrationGsmCellId] intValue];
}
else if (cellInfo[(NSString*)kCTRegistrationCellId])
{
CID = [cellInfo[(NSString*)kCTRegistrationCellId] intValue];
}
MCC = [[(NSString*)CTSIMSupportCopyMobileSubscriberCountryCode(NULL) autorelease] intValue];
MNC = [[(NSString*)CTSIMSupportCopyMobileSubscriberNetworkCode(NULL) autorelease] intValue];
}
}
3) This returns current serving cell tower
struct CTResult
{
int flag;
int a;
};
id _CTServerConnectionCreate(CFAllocatorRef, void*, int*);
#ifdef __LP64__
void _CTServerConnectionGetLocationAreaCode(id, int*);
void _CTServerConnectionGetCellID(id, int*);
#else
void _CTServerConnectionGetLocationAreaCode(struct CTResult*, id, int*);
#define _CTServerConnectionGetLocationAreaCode(connection, LAC) { struct CTResult res; _CTServerConnectionGetLocationAreaCode(&res, connection, LAC); }
void _CTServerConnectionGetCellID(struct CTResult*, id, int*);
#define _CTServerConnectionGetCellID(connection, CID) { struct CTResult res; _CTServerConnectionGetCellID(&res, connection, CID); }
#endif
...
int CID, LAC, MCC, MNC;
id CTConnection = _CTServerConnectionCreate(NULL, NULL, NULL);
_CTServerConnectionGetCellID(CTConnection, &CID);
_CTServerConnectionGetLocationAreaCode(CTConnection, &LAC);
MCC = [[(NSString*)CTSIMSupportCopyMobileSubscriberCountryCode(NULL) autorelease] intValue];
MNC = [[(NSString*)CTSIMSupportCopyMobileSubscriberNetworkCode(NULL) autorelease] intValue];
UPDATE
On ARM64 (iPhone 5S) there is an issue with all CoreTelephony functions that accept struct CTResult argument. Apparently, 64-bit version of CoreTelephony exports these functions without struct CTResult argument. Because of that you will get an error on ARM64 if you call these functions like you did in the past - arguments will be wrong. I updated function declarations so that they work on both 32-bit and 64-bit ARM architectures. I tested it and it works on both iPhone 4S and iPhone 5S.
This only applies to ARM64. If you build your project for 32-bit ARM architecture then there is no such issue. Your application will use 32-bit version of CoreTelephony which expects struct CTResult argument.
8.3 UPDATE
As of iOS 8.3 all of the above solutions require entitlement to work
<key>com.apple.CommCenter.fine-grained</key>
<array>
<string>spi</string>
</array>
Not only cell monitor is protected but it seems like all of the CoreTelephony notifications now require that entitlement to work. For example, kCTMessageReceivedNotification also affected.
suscriberCellularProvider is an object method (vs class method).
You can take a look how to use it here:
Determine iPhone user's country
I think CTCarrier has MCC and MNC.
You can check network type using the code from this question:
How to check if iPhone supports CDMA or GSM
And look this question for CellID:
CTServerConnectionGetCellID routine core telephony
The code below is how to insert to che entitlement to meke the code work on ios 8.3.
As of iOS 8.3 all of the above solutions require entitlement to work
<key>com.apple.CommCenter.fine-grained</key>
<array>
<string>spi</string>
</array>
Indeed, tha above code mentioned is said that can be run to get the lac and cell on ios 8.3 and above. But I really don't know how to insert the above on a jailbroken phone. Could anyone give any detail information.

What to use for iOS compiler define

I have the following code that I want to run on Iphone OS, what compiler flag should I use for IOS and where in the below code should it be inserted? Thanks
#if defined(__BORLANDC__) || defined (__WATCOMC__) || defined(_MSC_VER) || defined(__ZTC__) || defined(__HIGHC__) || defined(_TURBOC_)
typedef long int Word32 ;
typedef short int Word16 ;
typedef short int Flag ;
#elif defined( __sun)
typedef short Word16;
typedef long Word32;
typedef int Flag;
#elif defined(__unix__) || defined(__unix)
typedef short Word16;
typedef int Word32;
typedef int Flag;
#elif defined(VMS) || defined(__VMS)
typedef short Word16;
typedef long Word32;
typedef int Flag;
#else
#error COMPILER NOT TESTED typedef.h needs to be updated, see readme
#endif
For iOS/tvOS/watchOS, you can use:
#if (TARGET_OS_IPHONE)
For iOS, you can use:
#if (TARGET_OS_IOS)
and for MAC OS X:
#if (TARGET_OS_OSX)
Hope this helps.

Resources