I'm trying to make a c program which triggers CVE-2017-10661.
As far as I understand because might_cancel mechanism it isn't properly protected if you make parallel operations on the file descriptor you can cause a crash.
I believe these parallel operations are read, poll etc right?
Currently i have written this piece of code.
#include <sys/timerfd.h>
#include <sys/poll.h>
#include <sys/epoll.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
int main(int ac, char *av[])
{
int timerfd;
int epollfd;
struct itimerspec timerValue;
uint64_t exp;
ssize_t s;
/* set timerfd */
timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
if (timerfd < 0) {
printf("failed to create timer fd\n");
exit(1);
}
bzero(&timerValue, sizeof(timerValue));
timerValue.it_value.tv_sec = 1;
timerValue.it_value.tv_nsec = 0;
timerValue.it_interval.tv_sec = 1;
timerValue.it_interval.tv_nsec = 0;
/* start timer */
if (timerfd_settime(timerfd, 0, &timerValue, NULL) < 0) {
printf("could not start timer\n");
exit(1);
}
s = read( timerfd, &exp, sizeof(uint64_t));
exit(0);
}
As you can see i set up a timer and then i only do a reading operation. Is there any way t trigger the bug by doing mupltiple read or pollings?
The race condition is triggered by timerfd_settime() -> timerfd_setup_cancel() -> timerfd_setup_cancel(). So you should use multiple threads to do timerfd_settime with the flag as TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET.
Here is the POC I found online.
Related
I am developing a cross-platform mobile game (iOS and Android) using cocos2d-x.
Most of my code is written in C++, with OS specific code in Objective-C / Java / Swift using a bridge.
I was wondering if anyone has used any C++ library to host a UDP server within their app ?
EDIT: So far I have found many platform specific solutions (using Java for Android, and cocoaasync etc for iOS), but nothing specifically in C++ which has been used for a cross platform app.
Edit: I would prefer a solution without boost. Preferably something simple to include like adding a couple of files to a project.
You can most probably use Valve's GameNetworkingSockets, https://github.com/ValveSoftware/GameNetworkingSockets
They have very limited external dependencies, so you should be able to compile them for both iOS and Android
You can also take a look at this list: https://github.com/MFatihMAR/Awesome-Game-Networking, where there is a list of libraries that you can alternatively try.
You can use ASIO Standalone library. It is the same library available as boost/asio, but it doesn't require any other boost libraries. I have used boost/asio in exactly this type of project (Android/iOS) and it is by far the most superior solution.
Here is what I ended up with:
h file:
#include "Queue.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <array>
#include <iostream>
#include <thread>
using namespace std;
#define MAXBUFFER_SIZE 1024
class UDPServer {
public:
/**
* Constructor
*
* #port the port on which the UDP server is listening for packets.
*/
explicit UDPServer(unsigned short port);
/**
* Destructor
*/
~UDPServer() = default;
/**
* Setup the server.
*/
void setupServer();
/**
* Get a single message.
* For demonstration purposes, our messages is expected to be a array of int
*/
bool getMessage(std::array<int, 4>& message);
bool getIPAddress(std::array<int, 4>& message);
void setFoundIP();
bool isReady();
void nextPort();
int getPort();
private:
bool _isBoundToPort = false;
/**
* The server port.
*/
unsigned short port_;
bool isFoundIP = false;
/**
* The thread-safe message queue.
*/
Queue queue_;
Queue _ipAddresses;
/**
* The UDP server function.
*/
int UDPServerFunc();
};
cpp file:
#include "UDPServer.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
using namespace std;
/**
* This function parses an incoming message with the following format: 1;234;-89;-53;
*
* A valid message consists of 4 integer values separated by semicolons.
*/
inline std::array<int, 4> parseMessage(const std::string& input);
inline std::array<int,4> parseIp(const std::string& input);
UDPServer::UDPServer(unsigned short port) {
port_ = port;
}
bool UDPServer::getMessage(std::array<int, 4>& message) {
return queue_.pop(message);
}
bool UDPServer::getIPAddress(std::array<int, 4>& message) {
return _ipAddresses.pop(message);
}
void UDPServer::setFoundIP(){
isFoundIP = true;
}
bool UDPServer::isReady(){
return _isBoundToPort;
}
void UDPServer::nextPort(){
port_++;
}
int UDPServer::getPort(){
return port_;
}
void UDPServer::setupServer() {
// Launch the server thread.
std::thread t([this](){
UDPServerFunc();
});
t.detach();
}
int UDPServer::UDPServerFunc() {
// Creating socket file descriptor
int sockfd;
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// Filling server information
struct sockaddr_in servaddr, cliaddr;
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
servaddr.sin_family = AF_INET; // IPv
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(port_);
// Bind the socket with the server address
if (::bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
_isBoundToPort = true;
while (true) {
// Read the next message from the socket.
char message[MAXBUFFER_SIZE];
socklen_t len = sizeof(struct sockaddr);
ssize_t n = recvfrom(sockfd, (char *)&message, MAXBUFFER_SIZE, MSG_DONTWAIT,
(struct sockaddr *)&cliaddr, (socklen_t*)&len);
if (n > 0) {
message[n] = '\0';
// Parse incoming data and push the result on the queue.
// Parsed messages are represented as a std::array<int, 4>.
if(!isFoundIP){
_ipAddresses.push(parseIp(message));
}else{
queue_.push(parseMessage(message));
}
} else {
// Wait a fraction of a millisecond for the next message.
usleep(100);
}
}
return 0;
}
I removed any unnecessary code from my answer, as the meat really is just the code above. If anyone needs the extraneous functions as well, I shared the code on Github, and will add some examples later on too.
The above code is really simple and has a couple of parse functions for extracting an IP address, or a set of four numbers delimited by semicolons. The above code is simple enough to modify yourself for your own custom messages.
Queue.h is just a simple thread safe queue.
This is my first question, the reason i signed up to the site. I'm developing a game using Qt 5.9 and I use QTimer to spawn enemies on the screen. Everytime the timer's timeout function is called, an enemy is spawned.
What i try to do is if a player kills let's say 10 enemies, the timer interval decreases, so the enemies will spawn more frequently, making the game a little bit more challenging. The first time the timer interval is set, the game runs perfectly, but the second time the setInterval() method is called, when the player kills 10 enemies, the game suddenly crashes. I tried debugging it to figure out what might cause it, and it seems that it crashes when i try to set the spawnInterval.
I'm fairly new to coding so any advice is appreciated! Here are the relevant source files and codes from my code:
main.cpp
#include <QApplication>
#include <game.h>
Game * game;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
game = new Game();
game->show();
return a.exec();
}
game.h:
#include <QGraphicsScene>
#include <QWidget>
#include <QGraphicsView>
#include "Player.h"
#include "score.h"
#include "Health.h"
class Game: public QGraphicsView{
public:
Game(QWidget * parent=0);
QGraphicsScene * scene;
Player * player;
Score * score;
Health * health;
void setSpawnInterval(int spawnValue);
int getSpawnInterval();
void setTimerInterval();
private:
int spawnInterval = 1000;
};
#endif // GAME_H
game.cpp:
QTimer * timer1 = new QTimer();
QObject::connect(timer1,SIGNAL(timeout()),player,SLOT(spawn()));
timer1->start(getSpawnInterval());
}
void Game::setSpawnInterval(int spawnValue){
//this is the part where it crashes
spawnInterval = spawnValue;
}
int Game::getSpawnInterval(){
return spawnInterval;
}
score.h
#ifndef SCORE_H
#define SCORE_H
#include <QGraphicsTextItem>
class Score: public QGraphicsTextItem{
public:
Score(QGraphicsItem * parent=0);
void increase();
int getScore();
private:
int score;
};
#endif // SCORE_H
score.cpp
#include "score.h"
#include <QFont>
#include "game.h"
#include <QTimer>
void Score::increase()
{
score++;
if(score > 3){
Game * game;
game->setSpawnInterval(200);}
//Draw the text to the display
setPlainText(QString("Score: ") + QString::number(score));
}
int Score::getScore()
{
return score;
}
player.h
#ifndef PLAYER_H
#define PLAYER_H
#include <QGraphicsRectItem>
#include <QEvent>
#include <QObject>
class Player: public QObject, public QGraphicsRectItem{
Q_OBJECT
public:
Player(QGraphicsItem * parent=0);
void keyPressEvent(QKeyEvent * event);
int jumpPhaseNumber = 0;
bool jumpRun = false;
public slots:
void spawn();
void jumpPhase();
};
#endif
player.cpp
void Player::spawn()
{
Enemy * enemy = new Enemy();
scene()->addItem(enemy);
}
Seems you are creating two instance of class game.
I suggest you to use static variables for accessing from multi classes.
add this class to your project:
.cpp
#include "settings.h"
int Settings::spawnInterval = 1000;
Settings::Settings(QObject *parent) : QObject(parent)
{
}
.h
#ifndef SETTINGS_H
#define SETTINGS_H
#include <QObject>
#include <QString>
class Settings : public QObject
{
Q_OBJECT
public:
explicit Settings(QObject *parent = 0);
static int spawnInterval;
};
#endif // SETTINGS_H
now we have a static variable name spawnInterval, you can access it (set/get) from any classes that include settings class like this:
#include <settings.h>
Settings::spawnInterval = 100; // set
int value = Settings::spawnInterval; //get
This line: Game * game; game->setSpawnInterval(200) causes your program to crash: you must initialize the game pointer; to fix this, for example, you can hold a reference (pointer) of game inside the Score class, thus letting you call setSpawnInterval; I would construct Score inside Game's constructor passing thisas a parameter; this saves you from creating a new class, as #aghilpro suggested. Actually a struct would be better since your information is public and accessible from other classes without the need to implement getters/setters.
I want to use the syscall of __NR_perf_event_open for my Android app.
The code runs normally on linux but does not work on Android.
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <perf_event.h>
#include <asm/unistd.h>
long perf_event_open( struct perf_event_attr *hw_event, pid_t pid,
int cpu, int group_fd, unsigned long flags )
{
int ret;
ret = syscall( __NR_perf_event_open, hw_event, pid, cpu,
group_fd, flags );
return ret;
}
int main() {
//In the main function, I call perf_event_open:
struct perf_event_attr pe;
int fd;
fd = perf_event_open(&pe, 0, -1, -1, 0);
...
}
However, the fd always return the value -1. When I use "errno.h", it gave the error informaiton of:EBADF:bad file descriptor.
you have not configured "struct perf_event_attr pe;" yet
because pid == -1 and cpu == -1 is not valid. you can check it in http://web.eece.maine.edu/~vweaver/projects/perf_events/perf_event_open.html
Im writing a programme that opens and openGL windows with an image and connects to my android device where the user uses the device as a sort of trackpad to pan and zoom in and out. All is working fine however the programme gets stuck in the glutMainLoop and will not proceed with accepting data from the device. Apparently glutIdleFunc is the solution to my problem however i cant see how to implement this in my code without getting a memory error? Could someone show me how to put the function into my code so it runs the connection code as well as the opengl stuff?
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <vrpn_Shared.h>
#include <vrpn_Analog.h>
#include <vector>
#include <GL/freeglut.h>
#include <imageviewer.h>
using namespace std;
int done = 0;
int accepted = 0; // Signals that the program should exit
unsigned tracker_stride = 1; // Every nth report will be printed
//-------------------------------------
// This section contains the data structure that holds information on
// the devices that are created. For each named device, a remote of each
// type analog is created.
class device_info {
public:
char *name;
vrpn_Analog_Remote *ana;
};
const unsigned MAX_DEVICES = 2;
//-------------------------------------
// This section contains the data structure that is used to determine how
// often to print a report for each sensor of each tracker. Each element
// contains a counter that is used by the callback routine to keep track
// of how many it has skipped. There is an element for each possible sensor.
// A new array of elements is created for each new tracker object, and a
// pointer to it is passed as the userdata pointer to the callback handlers.
class t_user_callback {
public:
char t_name[vrpn_MAX_TEXT_LEN];
vector<unsigned> t_counts ;
};
//Callback handlers
void VRPN_CALLBACK handle_analog (void *userdata, const vrpn_ANALOGCB a)
{
int i;
const char *name = (const char *)userdata;
printf("Input from %s:\n \n %5.0f", name, a.channel[0]);
for (i = 1; i < a.num_channel; i++) {
printf(" %5.0f \n", a.channel[1]);
}
printf(" \n");
}
int main (int argc, char * argv [])
{
int print_for_tracker = 1; // Print tracker reports?
int print_for_button = 1; // Print button reports?
int print_for_analog = 1; // Print analog reports?
int print_for_dial = 1; // Print dial reports?
int print_for_text = 1; // Print warning/error messages?
device_info device_list[MAX_DEVICES];
unsigned num_devices = 0;
int i;
// Parse arguments, creating objects
for (i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-notracker")) {
print_for_tracker = 0;
} else if (!strcmp(argv[i], "-nobutton")) {
print_for_button = 0;
} else if (!strcmp(argv[i], "-noanalog")) {
print_for_analog = 0;
} else if (!strcmp(argv[i], "-nodial")) {
print_for_dial = 0;
} else if (!strcmp(argv[i], "-notext")) {
print_for_text = 0;
} else if (!strcmp(argv[i], "-trackerstride")) {
if (tracker_stride <= 0) {
fprintf(stderr, "-trackerstride argument must be 1 or greater\n");
return -1;
}
} else { // Create a device and connect to it.
device_info *dev;
// Name the device and open it as everything
dev = &device_list[num_devices];
dev->name = argv[i];
dev->ana = new vrpn_Analog_Remote(dev->name);
if (print_for_analog) {
printf(" Analog");
dev->ana->register_change_handler(dev->name, handle_analog);
}
printf(".\n");
num_devices++;
}
}
// main interactive loop
printf("Press ^C to exit.\n");
while ( ! done ) {
unsigned i;
// Let all the devices do their things
for (i = 0; i < num_devices; i++) {
device_list[i].ana->mainloop();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_SINGLE);
glutInitWindowSize(400,300);
glutInitWindowPosition(200,100);
glutCreateWindow("ImageViewer");
init();
glutDisplayFunc(display);
glutMotionFunc(drag);
glutMouseFunc(mouse);
// glutIdleFunc(IdleFunc);
glutMainLoop();
}
}
return 0;
}
glut is fine if it can manage all of the input devices, and everything is event-driven from the inputs that it manages. Once you have unmanaged input devices or non-event-based processing, you probably want to use something other than glut. Your other alternative is to fork and run your asynchronous stuff in a separate process (or thread).
I have some problems when using the dynamic loading API (<dlfcn.h>: dlopen(), dlclose(), etc) on Android.
I'm using NDK standalone toolchain (version 8) to compile the applications and libraries.
The Android version is 2.2.1 Froyo.
Here is the source code of the simple shared library.
#include <stdio.h>
int iii = 0;
int *ptr = NULL;
__attribute__((constructor))
static void init()
{
iii = 653;
}
__attribute__((destructor))
static void cleanup()
{
}
int aaa(int i)
{
printf("aaa %d\n", iii);
}
Here is the program source code which uses the mentioned library.
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
void *handle;
typedef int (*func)(int);
func bbb;
printf("start...\n");
handle = dlopen("/data/testt/test.so", RTLD_LAZY);
if (!handle)
{
return 0;
}
bbb = (func)dlsym(handle, "aaa");
if (bbb == NULL)
{
return 0;
}
bbb(1);
dlclose(handle);
printf("exit...\n");
return 0;
}
With these sources everything is working fine, but when I try to use some STL functions or classes, the program crashes with a segmentation fault, when the main() function exits, for example when using this source code for the shared library.
#include <iostream>
using namespace std;
int iii = 0;
int *ptr = NULL;
__attribute__((constructor))
static void init()
{
iii = 653;
}
__attribute__((destructor))
static void cleanup()
{
}
int aaa(int i)
{
cout << iii << endl;
}
With this code, the program crashes with segmentation fault after or the during main() function exit.
I have tried couple of tests and found the following results.
Without using of STL everything is working fine.
When use STL and do not call dlclose() at the end, everything is working fine.
I tried to compile with various compilation flags like -fno-use-cxa-atexit or -fuse-cxa-atexit, the result is the same.
What is wrong in my code that uses the STL?
Looks like I found the reason of the bug. I have tried another example with the following source files:
Here is the source code of the simple class:
myclass.h
class MyClass
{
public:
MyClass();
~MyClass();
void Set();
void Show();
private:
int *pArray;
};
myclass.cpp
#include <stdio.h>
#include <stdlib.h>
#include "myclass.h"
MyClass::MyClass()
{
pArray = (int *)malloc(sizeof(int) * 5);
}
MyClass::~MyClass()
{
free(pArray);
pArray = NULL;
}
void MyClass::Set()
{
if (pArray != NULL)
{
pArray[0] = 0;
pArray[1] = 1;
pArray[2] = 2;
pArray[3] = 3;
pArray[4] = 4;
}
}
void MyClass::Show()
{
if (pArray != NULL)
{
for (int i = 0; i < 5; i++)
{
printf("pArray[%d] = %d\n", i, pArray[i]);
}
}
}
As you can see from the code I did not used any STL related stuff.
Here is the source files of the functions library exports.
func.h
#ifdef __cplusplus
extern "C" {
#endif
int SetBabe(int);
int ShowBabe(int);
#ifdef __cplusplus
}
#endif
func.cpp
#include <stdio.h>
#include "myclass.h"
#include "func.h"
MyClass cls;
__attribute__((constructor))
static void init()
{
}
__attribute__((destructor))
static void cleanup()
{
}
int SetBabe(int i)
{
cls.Set();
return i;
}
int ShowBabe(int i)
{
cls.Show();
return i;
}
And finally this is the source code of the programm that uses the library.
main.cpp
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include "../simple_lib/func.h"
int main()
{
void *handle;
typedef int (*func)(int);
func bbb;
printf("start...\n");
handle = dlopen("/data/testt/test.so", RTLD_LAZY);
if (!handle)
{
printf("%s\n", dlerror());
return 0;
}
bbb = (func)dlsym(handle, "SetBabe");
if (bbb == NULL)
{
printf("%s\n", dlerror());
return 0;
}
bbb(1);
bbb = (func)dlsym(handle, "ShowBabe");
if (bbb == NULL)
{
printf("%s\n", dlerror());
return 0;
}
bbb(1);
dlclose(handle);
printf("exit...\n");
return 0;
}
Again as you can see the program using the library also does not using any STL related stuff, but after run of the program I got the same segmentation fault during main(...) function exit. So the issue is not connected to STL itself, and it is hidden in some other place. Then after some long research I found the bug.
Normally the destructors of static C++ variables are called immediately before main(...) function exit, if they are defined in main program, or if they are defined in some library and you are using it, then the destructors should be called immediately before dlclose(...).
On Android OS all destructors(defined in main program or in some library you are using) of static C++ variables are called during main(...) function exit. So what happens in our case? We have cls static C++ variable defined in library we are using. Then immediately before main(...) function exit we call dlclose(...) function, as a result library closed and cls becomes non valid. But the pointer of cls is stored somewhere and it's destructor should be called during main(...) function exit, and because at the time of call it is already invalid, we get segmentation fault. So the solution is to not call dlclose(...) and everything should be fine. Unfortunately with this solution we cannot use attribute((destructor)) for deinitializing of something we want to deinitialize, because it is called as a result of dlclose(...) call.
I have a general aversion to calling dlclose(). The problem is that you must ensure that nothing will try to execute code in the shared library after it has been unmapped, or you will get a segmentation fault.
The most common way to fail is to create an object whose destructor is defined in or calls code defined in the shared library. If the object still exists after dlclose(), your app will crash when the object is deleted.
If you look at logcat you should see a debuggerd stack trace. If you can decode that with the arm-eabi-addr2line tool you should be able to determine if it's in a destructor, and if so, for what class. Alternatively, take the crash address, strip off the high 12 bits, and use that as an offset into the library that was dlclose()d and try to figure out what code lives at that address.
I encountered the same headache on Linux. A work-around that fixes my segfault is to put these lines in the same file as main(), so that dlclose() is called after main returns:
static void* handle = 0;
void myDLClose(void) __attribute__ ((destructor));
void myDLClose(void)
{
dlclose(handle);
}
int main()
{
handle = dlopen(...);
/* ... real work ... */
return 0;
}
The root cause of dlclose-induced segfault may be that a particular implementation of dlclose() does not clean up the global variables inside the shared object.
You need to compile with -fpic as a compiler flag for the application that is using dlopen() and dlclose(). You should also try error handling via dlerror() and perhaps checking if the assignment of your function pointer is valid, even if it's not NULL the function pointer could be pointing to something invalid from the initialization, dlsym() is not guaranteed to return NULL on android if it cannot find a symbol. Refer to the android documentation opposed to the posix compliant stuff, not everything is posix compliant on android.
You should use extern "C" to declare you function aaa()