Problem
I'm attempting to create a buffer overflow in order to learn more about Address Sanitizer. I've written the following code which I thought would create a buffer overflow, though I must be mistaken as it's not throwing the expected "Heap buffer overflow detected".
Attempt
var ints : [UInt8] = [ 1, 2, 3, 4 ]
let a = UnsafeMutableBufferPointer(start: &ints, count: ints.count)
a[28] = 17 // array out of index
I've enabled Address Sanitizer in Xcode by clicking my application > Edit Scheme... and then "Enable Address Sanitizer". Then I rebuilt my application before running.
Question
How do I create a buffer overflow in Swift 2?
From https://developer.apple.com/videos/play/wwdc2015-413/?time=947
Address Sanitizer is an LLVM tool for C-based languages.
and https://developer.apple.com/videos/play/wwdc2015-413/?time=1422
In order to use Address Sanitizer, Xcode passes a special flag to clang.
It seems that the Address Sanitizer is only available with clang
for C, Objective-C etc., but not with the Swift compiler swiftc.
A simple C program which triggers a buffer overflow is
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[]) {
int *p = malloc(4 * sizeof(int));
p[28] = 17;
return 0;
}
Related
I am quite new to using pcap lib, so please bear with me.
I am trying to use pcap_getnonblock function, the documentation says the following:
pcap_getnonblock() returns the current 'non-blocking' state of
the capture descriptor; it always returns 0 on 'savefiles' . If
there is an error, PCAP_ERROR is returned and errbuf is filled in
with an appropriate error message.
errbuf is assumed to be able to hold at least PCAP_ERRBUF_SIZE
chars.
I got -3 returned and the errbuf is an empty string, I couldn't understand the meaning of such result.
I believe this caused a socket error: 10065.
This problem happened only once and I could not reproduce it, but still it would be great to find its causing to prevent it in future executions.
Thanks in advance.
pcap_getnonblock() can return -3 - that's PCAP_ERROR_NOT_ACTIVATED. Unfortunately, that's not documented; I'll fix that.
Here's a minimal reproducible example that demonstrates this:
#include <pcap/pcap.h>
#include <stdio.h>
int
main(int argc, char **argv)
{
pcap_t *pcap;
char errbuf[PCAP_ERRBUF_SIZE];
if (argc != 2) {
fprintf(stderr, "Usage: this_program <interface_name>\n");
return 1;
}
pcap = pcap_create(argv[1], errbuf);
if (pcap == NULL) {
fprintf(stderr, "this_program: pcap_create(%s) failed: %s\n",
argv[1], errbuf);
return 2;
}
printf("pcap_getnonblock() returns %d on non-activated pcap_t\n",
pcap_getnonblock(pcap, errbuf));
return 0;
}
(yes, that's minimal, as 1) names of interfaces are OS-dependent, so it has to be a command-line argument and 2) if you don't run the program correctly, it should let you know what's happening, so you know what you have to do in order to reproduce the problem).
Perhaps pcap_getnonblock() and pcap_setnonblock() should be changed so that you can set non-blocking mode before activating the pcap_t, so that, when activated, it will be in non-blocking mode. It doesn't work that way currently, however.
I.e., you're allocating a pcap_t with pcap_create(), but you're not activating it with pcap_activate(). You need to do both in order to have a pcap_t on which you can capture.
I build a code in Xcode console with C++ project works perfectly before:
#include "SerialPort.hpp"
#include "TypeAbbreviations.hpp"
#include <iostream>
int main(int argc, const char * argv[]) {
//* Open port, and connect to a device
const char devicePathStr[] = "/dev/tty.usbserial-A104RXG4";
const int baudRate = 9600;
int sfd = openAndConfigureSerialPort(devicePathStr, baudRate);
if (sfd < 0) {
if (sfd == -1) {
printf("Unable to connect to serial port.\n");
}
else { //sfd == -2
printf("Error setting serial port attributes.\n");
}
return 0;
}
// * Read using readSerialData(char* bytes, size_t length)
// * Write using writeSerialData(const char* bytes, size_t length)
// * Remember to flush potentially buffered data when necessary
// * Close serial port when done
const char dataToWrite[]="abcd";
char databuffer[1024];
while(1){
readSerialData(databuffer, 4);
sleep(2);
writeSerialData(databuffer, 4);
sleep(2);
}
printf("end.\n");
return 0;
}
After this build, I tried to migrate it to my Xcode cocoa application with C++ wrappers below.
I am pretty sure my Wrapper works fine with test C++ code. That means, I can call C++ function from my ViewController.swift.
But there's one strange thing happened. I am not able to open connection with the following code:
sfd = open(portPath, (O_RDWR | O_NOCTTY | O_NDELAY));
if (sfd == -1) {
printf("Unable to open serial port: %s at baud rate: %d\n", portPath, baudRate);
printf("%s", std::strerror(errno));
return sfd;
}
There error message returns :
Unable to open serial port: /dev/tty.usbserial-A104RXG4 at baud rate: 9600
Operation not permitted
I've tried to change app sandbox configuration, set up my system preference to grant access to my app, also I disabled my rootless. (csrutil disable with command + R)
But the problem still persists:
&
I want to ask that:
1. Why my code on Xcode C++ project works fine but fail on swift's cocoa app on Xcode?
2. How to solve the "Operation not permitted" Issue.
My Xcode version is 11.3.1 and Mac OS is 10.14.6 Mojave.
I figure it out myself.
It's APP sandbox is bothering me.
All you need to do is turn off sandbox
Turn off it by click X on the mouse point.
If you want to add it back, just click +Capability and put it back on.
https://i.stack.imgur.com/ZOc18.jpg
reference : https://forums.developer.apple.com/thread/94177#285075
I am new to modbus. I have spent hours reading the Help(?) files, which never seem to give you an example! I am using C on a Raspberry Pi, model3 and have installed libmodbus. I am trying to talk to an epSolar solar panel controller via an FTDI USB to RS485 converter.
The epSolar docs say that the Read Input registers start at address 3000 and continue to 311D. I am trying to read 3104.
I modified the code below. It connects to the device but trying to read input register 0x04 always returns -1:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <modbus.h>
enum {TCP, RTU};
int main(int argc, char *argv[])
{
int socket;
modbus_t *ctx;
modbus_mapping_t *mb_mapping;
int rc;
int use_backend;
int i;
uint16_t tab_reg[64];
use_backend = RTU;
printf("Waiting for Serial connection\n");
ctx = modbus_new_rtu("/dev/SOLAR", 115200, 'N', 8, 1);
modbus_set_slave(ctx, 0);
//modbus_connect(ctx);
if(modbus_connect(ctx) == -1)
{
fprintf(stderr, "Serial connection failed:
%s\n", modbus_strerror(errno));
modbus_free(ctx);
return -1;
}
printf("Serial connection started!\n");
mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0,
MODBUS_MAX_READ_REGISTERS, 0);
if(mb_mapping == NULL)
{
fprintf(stderr, "Failed to allocate the mapping: %s\n",
modbus_strerror(errno));
modbus_free(ctx);
return -1;
}
rc = modbus_read_input_registers(ctx, 1, 0x0A, tab_reg);
if(rc == -1)
{
fprintf(stderr, "%s\n", modbus_strerror(errno));
return -1;
}
for(i=0; i < rc; i++)
printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
modbus_mapping_free(mb_mapping);
modbus_free(ctx);
modbus_close(ctx);
return 0;
}
It connects fine and allocates the mapping, but rc is always -1 with error message that the port has timed out.
I have run out of ideas and feel like I am navigating through treacle!
Any help most appreciated.
I am also new to Modbus. With my current experience, make sure you are allocating enough memory for the tab_reg for storing the results. Also try setting the Debug mode on i.e modbus_set_debug(ctx, TRUE); to Check for the request and response code.
I know this is a really old question, but hopefully this answer will help anyone who lands here via a Google search.
I can see a few points that need some help.
As commented by Saad above, the modbus server ID above is incorrect. ID 0 is reserved for broadcast messages, which a slave will not respond to. Find out what the Modbus ID for the target device is, and use that.
I think what's tricking you is that you'll also always get a proper "connect" as long as the serial port you provided is valid. This isn't a connection to any particular device so much as it's a connection to the Modbus network port. You're getting a timeout because a response was expected by libmodbus, but no response was received on the wire.
There are several other little troubles in the code presented, but given the age of this post I almost feel like I'm nitpicking something the OP probably already solved. The big problem is the unworkable slave ID. Other minor problems include: unnecessary use of modbus_mapping (struct for use on server/slaves), possible misallocation of modbus_mapping (no space allocated for input registers).
I'm using Eclipse 4.2, with CDT, and MinGW toolchain on a Windows machine (although I've a feeling the problem has nothing to do with this specific configuration). The G++ compiler is 4.7
I'm playing with c++11 features, with the following code:
#include <iostream>
#include <iomanip>
#include <memory>
#include <vector>
#include <list>
#include <algorithm>
using namespace std;
int main( int argc, char* argv[] )
{
vector<int> v { 1, 2, 3, 4, 5, 6, 7 };
int x {5};
auto mark = remove_if( v.begin(), v.end(), [x](int n) { return n<x; } );
v.erase( mark, v.end() );
for( int x : v ) { cout << x << ", "; }
cout << endl;
}
Everything is very straight forward and idiomatic c++11. The code compiles with no problems on the command line (g++ -std=c++11 hello.cpp).
In order to make this code compile In eclipse, I set the compiler to support C++11:
Properties -> C/C++ Build -> Settings -> Miscellaneous -> Ohter Flags:
I'm adding -std=c++11
Properties -> C/C++Build -> Discovery Options -> Compiler invocation arguments:
Adding -std=c++11
That's the only change I did to either the global preferences or to the project properties.
First Question: Why do I've to change the flags in two places? When each compiler flags is used?
If I hit Ctrl-B, the project will build successfully, as expected, and running it from within eclipse show the expected result (It prints: '5, 6, 7,').
However, the editor view shows red marks of error on both the 'remove_if' line, and the 'v.erase' line. Similarly, the Problems view shows I've these two problems. Looking at the details of the problem, I get:
For the remove_if line: 'Invalid arguments. Candidates are: #0 remove_if(#0, #0, #1)
For the erase line: 'Invalid arguments Candidates are: '? erase(?), ? erase(?,?)'
Second questions: It appears there are two different builds: one for continues status, and one for the actual build. Is that right? If so, do they have different rule (compilation flags, include paths, etc.)?
Third question: In the problem details I also see: 'Name resolution problem found by the indexer'. I guess this is why the error message are so cryptic. Are those messages coming from MinGW g++ compiler or from Eclipse? What is this Name resolution? How do I fix?
Appreciate your help.
EDIT (in reply to #Eugene): Thank you Eugene. I've opened a bug on Eclipse. I think that C++11 is only partially to blame. I've cleaned my code from C++11 stuff, and removed the -std=c++11 flag from both compilation switch. And yet, the CodAn barks on the remove_if line:
int pred( int n ) { return n < 5; }
int main( int argc, char* argv[] )
{
vector<int> v;
for( int i=0; i<=7; ++i ) {
v.push_back( i );
}
vector<int>::iterator mark = remove_if( v.begin(), v.end(), pred );
v.erase( mark, v.end() );
for( vector<int>::iterator i = v.begin(); i != v.end(); ++i ) {
cout << *i << ", ";
}
cout << endl;
}
The code compiles just fine (with Ctrl-B), but CodAn doesn't like the remove_if line, saying: Invalid Arguments, Candidates are '#0 remove_if(#0,#0,#1)'.
This is a very cryptic message - it appears it misses to substitute arguments in format string (#0 for 'iterator' and #1 for 'predicate'). I'm going to update the bug.
Interestingly, using 'list' instead of 'vector' clears up the error.
However, as for my question, I'm curious about how the CodAn work. Does it uses g++ (with a customized set of flags), or another external tool (lint?), or does it do it internally in Java? If there is a tool, how can I get its command line argument, and its output?
Build/Settings - these flags will be included into your makefile to do actual build. Build/Discovery - these flags will be passed to a compiler when "scanner settings" are discovered by IDE. IDE will run compiler in a special mode to discover values of the predefined macros, include paths, etc.
I believe, the problems you are seeing are detected by "Codan". Codan is a static analysis built into the CDT editor, you may find its settings on "C/C++ General"/"Code Analysis". You should report the problem to the bugs.eclipse.org if you feel the errors shown are bogus. Note that CDT does not yet support all C++11 features.
I'm trying to pass arguments in XCode and understand you need to add them from the Args tab, using the Get Info button, in the Executables of the Groups and Files pane. I'm trying to see if I can get it to work, but am having some difficulty. My program is simply:
#include <iostream>
#include <ostream>
using namespace std;
int main(int argc, char *argv[]) {
for (int i = 0; i < argc; i++) {
cout << argv[i];
}
return 0;
}
And in the Args tab, I have the number 2 and then in another line the number 1. I do not get any output when I run the program. What am I doing wrong? Thanks!
Your code works fine and it displays the arguments.
You may want to print a new line after each argument to make the output more readable:
cout << argv[i] << "\n";
Output is visible in the console (use Command+Shift+R to bring up the console).