-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.c
411 lines (363 loc) · 11.1 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// (Vulnerable) quote_db
// Created in preparation for OSED
// William Moody, 06.06.2021
// Compile (DEP, ASLR enabled):
// gcc main.c -o main.exe -l ws2_32 -Wl,--nxcompat,--dynamicbase
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <winsock2.h>
#include <windows.h>
#include <memory.h>
#include <time.h>
#pragma comment(lib, "ws2_32.lib")
#define VERSION 10
#define DEFAULT_PORT 3700
#define MAX_CONNECTIONS 1
#define BUF_SIZE 16384
#define QUOTE_SIZE 2048
#define MAX_NUM_QUOTES 100
// Array to hold quotes
char quotes[MAX_NUM_QUOTES][QUOTE_SIZE];
int num_quotes;
/**
* Displays a server banner in the console
*/
void banner()
{
printf("+===========================+\n");
printf("| quote_db v%*.*f |\n", 2, 2, VERSION / 10.f);
printf("| William Moody, 06.06.2021 |\n");
printf("+===========================+\n\n");
}
/**
* Displays a help message and exits the program
*
* @param prog_name Name of the program (argv[0])
*/
void usage(char *prog_name)
{
printf("Usage: %s [-p PORT] [-h]\n", prog_name);
exit(1);
}
/**
* Adds a quote
*
* @param quote The quote to add to the db
* @returns index of the quote which was added
*/
int add_quote(char *quote)
{
printf("[?] Adding quote to db...");
memset(quotes[num_quotes], 0, QUOTE_SIZE);
printf("#%d.\n", num_quotes);
int copy_size = strlen(quote);
copy_size = (copy_size > QUOTE_SIZE) ? QUOTE_SIZE : copy_size;
memcpy(quotes[num_quotes], quote, copy_size);
return num_quotes++;
}
/**
* Gets a quote by index
*
* @param index Index of the quote to give
* @param quote Buffer to move to quote into
* @returns a quote
*/
int get_quote(int index, char **quote)
{
printf("[?] Getting quote #%d from db...\n", index);
snprintf(*quote, QUOTE_SIZE, quotes[index]);
return strlen(quotes[index]);
}
/**
* Updates a quote by index
*
* @param index Index of the quote to update
* @param quote New quote to replace the old one with
*/
void update_quote(int index, char *quote)
{
printf("[?] Updating quote with index #%d...\n", index);
memset(quotes[index], 0, QUOTE_SIZE);
memcpy(quotes[index], quote, strlen(quote));
return;
}
/**
* Deletes a quote by index
*
* @param index Index of the quote to remove
*/
void delete_quote(int index)
{
printf("[?] Deleting quote with index #%d...\n", index);
for (int i = index; i < MAX_NUM_QUOTES - 1; i++)
{
memset(quotes[i + 1], 0, QUOTE_SIZE);
memcpy(quotes[i + 1], quotes[i], strlen(quotes[i]));
}
num_quotes--;
return;
}
/**
* Logs a bad request for debugging purposes
*
* @param request The request which was made
*/
void log_bad_request(char *request)
{
char bad_request[QUOTE_SIZE];
memset(bad_request, 0, QUOTE_SIZE);
memcpy(bad_request, request, BUF_SIZE);
printf("....[%d] invalid request=%s\n", GetCurrentThreadId(), bad_request);
}
/**
* Thread - Handles a client connection
*
* @param sock The client socket
*/
void handle_connection(void *sock)
{
// Create a buffer to store the incoming packet
// and init with 0's
char buf[BUF_SIZE];
memset(buf, 0, BUF_SIZE);
// Receive the packet
int recvlen;
if ((recvlen = recv((SOCKET)sock, buf, BUF_SIZE, 0)) < 4)
{
printf("....[%d] recv failed.\n", GetCurrentThreadId());
closesocket((SOCKET)sock);
return;
}
printf("....[%d] received %d bytes.\n", GetCurrentThreadId(), recvlen);
// Check what opcode the client is calling
unsigned int opcode;
memcpy(&opcode, (void *)buf, sizeof(unsigned int));
printf("....[%d] opcode=%d\n", GetCurrentThreadId(), opcode);
// Create a buffer to hold response
char response[BUF_SIZE];
memset(response, 0, BUF_SIZE);
unsigned response_size = 0;
// Some definitions for variables used
// in the switch statement
char *quote;
unsigned int quote_index;
char new_quote[QUOTE_SIZE];
char *index_out_of_bounds_msg = "INDEX_OUT_OF_BOUNDS";
char *bad_request_msg = "BAD_REQUEST";
char *max_quotes_reached_msg = "MAX_NUM_QUOTES_REACHED";
switch (opcode)
{
case 900:;
// Ask for a random quote
time_t t;
srand((unsigned)time(&t));
//response_size = get_quote(rand() % num_quotes, "e);
//memcpy(response, quote, response_size);
break;
case 901:;
// Ask for a specific quote
memcpy("e_index, (void *)(buf + 4), sizeof(unsigned int));
if (quote_index >= num_quotes)
{
response_size = strlen(index_out_of_bounds_msg);
memcpy(response, index_out_of_bounds_msg, response_size);
}
else
{
quote = malloc(QUOTE_SIZE);
response_size = get_quote(quote_index, "e);
memcpy(response, quote, response_size);
}
break;
case 902:;
// Add a new quote
if (num_quotes < MAX_NUM_QUOTES)
{
memcpy(new_quote, buf + 4, QUOTE_SIZE);
quote_index = add_quote(new_quote);
response_size = sizeof(unsigned int);
memcpy((void *)response, "e_index, response_size);
}
else
{
response_size = strlen(max_quotes_reached_msg);
memcpy(response, max_quotes_reached_msg, response_size);
}
break;
case 903:;
// Update a specific quote
memcpy("e_index, (void *)(buf + 4), sizeof(unsigned int));
if (quote_index >= num_quotes)
{
response_size = strlen(index_out_of_bounds_msg);
memcpy(response, index_out_of_bounds_msg, response_size);
}
else
{
update_quote(quote_index, buf + 8);
}
break;
case 904:;
// Delete a specific quote
memcpy("e_index, (void *)(buf + 4), sizeof(unsigned int));
if (quote_index >= num_quotes)
{
response_size = strlen(index_out_of_bounds_msg);
memcpy(response, index_out_of_bounds_msg, response_size);
}
else
{
delete_quote(quote_index);
}
break;
default:;
// Default case (invalid opcode).
log_bad_request(buf + 4);
response_size = strlen(bad_request_msg);
memcpy(response, bad_request_msg, strlen(bad_request_msg));
break;
}
// Send a response if we need to
if (response_size > 0)
{
int sent_bytes;
if ((sent_bytes = send((SOCKET)sock, response, response_size, 0)) == SOCKET_ERROR)
{
printf("....[%d] failed while sending response.\n", GetCurrentThreadId());
closesocket((SOCKET)sock);
return;
}
printf("....[%d] sent response (%d bytes).\n", GetCurrentThreadId(), sent_bytes);
}
// Close the client connection and return
closesocket((SOCKET)sock);
printf("....[%d] ended connection.\n", GetCurrentThreadId());
return;
}
/**
* Starts the server on a given port
*
* @param port Port to start the server on
* @returns -1 if the server failed to start on the given port
*/
int start_server(int port)
{
// Display welcome banner
banner();
// Init quote array
VirtualAlloc(quotes, sizeof(char[QUOTE_SIZE]) * MAX_NUM_QUOTES, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
memset(quotes, 0, sizeof(char[QUOTE_SIZE]) * MAX_NUM_QUOTES);
num_quotes = 0;
// Add some sample quotes
add_quote("If life were predictable it would cease to be life, and be without flavor. - Eleanor Roosevelt");
add_quote("Give a man a mask and he'll tell you the truth. - Oscar Wilde");
add_quote("Do not go where the path may lead, go instead where there is no path and leave a trail. - Ralph Waldo Emerson");
add_quote("Always remember that you are absolutely unique. Just like everyone else. - Margaret Mead");
add_quote("If you do not change direction, you may end up where you are heading. - Lao Tzu");
add_quote("No one has ever failed until he has given up. - Anonymous");
add_quote("Believe you can you're halfway there. - Theodore Roosevelt");
add_quote("Do it today or regret it tomorrow. - Anonymous");
add_quote("Action is the foundation key to all success. - Pablo Picasso");
add_quote("The only place were success comes before work is in the dictionary. - Vidal Sassoon");
// Try to initialize the winsock library
WSADATA wsa;
if (WSAStartup(0x22, &wsa) != 0)
{
printf("[-] Failed to initialize WSA library\n");
return -1;
}
printf("[+] WSA Initialized.\n");
// Try to create socket
SOCKET s;
if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
printf("[-] Failed to created socket.\n");
closesocket(s);
return -1;
}
printf("[+] Socket created.\n");
// Bind socket to the given port
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(port);
if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
{
printf("[-] Failed to bind to port %d.\n", port);
closesocket(s);
return -1;
}
printf("[+] Bound to port %d.\n", port);
// Listen for incoming connection
listen(s, MAX_CONNECTIONS);
printf("[+] Listening for incoming connections...\n");
// Accept connections and create handler threads
struct sockaddr_in client;
int c = sizeof(struct sockaddr_in);
SOCKET client_socket;
while ((client_socket = accept(s, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
{
printf("[+] Accepted a connection from %s:%d.\n", inet_ntoa(client.sin_addr), ntohs(client.sin_port));
_beginthread(&handle_connection, 0, (void *)client_socket);
}
if (client_socket == INVALID_SOCKET)
{
printf("[-] Error while accepting socket.\n");
closesocket(s);
closesocket(client_socket);
return -1;
}
// Close the server socket
closesocket(s);
// Close server without errors
return 0;
}
/**
* Required to initialize the console
*/
asm("or %esp, %eax; ret");
asm("mov (%eax), %eax; add $5, %ecx; pop %edx; ret");
asm("mov %eax, %ebx; ret");
asm("xchg %esp, %ebx; dec %ecx; ret");
asm("mov %eax, (%ebx); ret");
asm("xchg %ebx, %edx; cmp %eax, %ebx; ret");
asm("add $4, %ebx; ret");
asm("add %ecx, %edx; ret");
/**
* Entry point
* Handles arguments and starts the server
*
* __declspec(dllexport) is a workaround so that mingw actually
* compiles with ASLR
*/
__declspec(dllexport) int main(int argc, char *argv[])
{
// Init port to default value
int port = DEFAULT_PORT;
// Parse arguments
int opt;
while ((opt = getopt(argc, argv, "p:h")) >= 0)
{
switch (opt)
{
case 'p':
// Set the server port number
if (sscanf(optarg, "%i", &port) != 1)
usage(argv[0]);
break;
case 'h':
// Display the help message
usage(argv[0]);
break;
default:
break;
}
}
// Start the server
start_server(port);
// Cleanup winsock2 library
WSACleanup();
// Exit with no errors
return 0;
}