### C: Heap Memory Allocation and Deallocation Example Source: https://context7.com/intere/hacking/llms.txt Demonstrates dynamic memory allocation and deallocation using malloc() and free(). It handles potential allocation failures and shows memory reuse. Input is taken from command-line arguments for memory size. ```c #include #include #include int main(int argc, char *argv[]) { char *char_ptr; int *int_ptr; int mem_size; if (argc < 2) mem_size = 50; else mem_size = atoi(argv[1]); printf("[+] allocating %d bytes for char_ptr\n", mem_size); char_ptr = (char *) malloc(mem_size); if(char_ptr == NULL) { fprintf(stderr, "Error: could not allocate heap memory.\n"); exit(-1); } strcpy(char_ptr, "This memory is on the heap."); printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr); printf("[+] allocating 12 bytes for int_ptr\n"); int_ptr = (int *) malloc(12); if(int_ptr == NULL) { fprintf(stderr, "Error: could not allocate heap memory.\n"); exit(-1); } *int_ptr = 31337; printf("int_ptr (%p) --> %d\n", int_ptr, *int_ptr); printf("[-] freeing char_ptr's heap memory...\n"); free(char_ptr); printf("[+] allocating another 15 bytes for char_ptr\n"); char_ptr = (char *) malloc(15); strcpy(char_ptr, "new memory"); printf("char_ptr (%p) --> '%s'\n", char_ptr, char_ptr); free(int_ptr); free(char_ptr); return 0; } // Compile and run: // gcc -o heap_example heap_example.c // ./heap_example 100 ``` -------------------------------- ### Buffer Overflow Demonstration (C) Source: https://context7.com/intere/hacking/llms.txt Illustrates buffer overflow by using `strcpy` without bounds checking, showing how writing beyond allocated memory can corrupt adjacent variables. This example requires command-line arguments for input. ```c #include #include int main(int argc, char *argv[]) { int value = 5; char buffer_one[8], buffer_two[8]; strcpy(buffer_one, "one"); strcpy(buffer_two, "two"); printf("[BEFORE] buffer_two is at %p and contains '%s'\n", buffer_two, buffer_two); printf("[BEFORE] buffer_one is at %p and contains '%s'\n", buffer_one, buffer_one); printf("[BEFORE] value is at %p and is %d (0x%08x)\n", &value, value, value); printf("\n[STRCPY] copying %d bytes into buffer_two\n\n", strlen(argv[1])); strcpy(buffer_two, argv[1]); // Vulnerable copy - no bounds checking printf("[AFTER] buffer_two is at %p and contains '%s'\n", buffer_two, buffer_two); printf("[AFTER] buffer_one is at %p and contains '%s'\n", buffer_one, buffer_one); printf("[AFTER] value is at %p and is %d (0x%08x)\n", &value, value, value); return 0; } // Compile: gcc -o overflow_example overflow_example.c // Run with safe input: ./overflow_example AAAA // Run with overflow: ./overflow_example AAAAAAAAAAAAAAAAAAAAAAAA ``` -------------------------------- ### C Tiny Web Server Implementation Source: https://context7.com/intere/hacking/llms.txt This C code defines a simple HTTP/1.0 web server. It includes functions to get file sizes, handle client connections, parse requests, and serve static files. Dependencies include standard C libraries and custom 'hacking.h' and 'hacking-network.h' headers. It expects a 'webroot' directory for files and handles GET/HEAD requests. ```c #include #include #include #include #include #include #include #include #include "hacking.h" #include "hacking-network.h" #define PORT 80 #define WEBROOT "./webroot" int get_file_size(int fd) { struct stat stat_struct; if(fstat(fd, &stat_struct) == -1) return -1; return (int) stat_struct.st_size; } void handle_connection(int sockfd, struct sockaddr_in *client_addr_ptr) { unsigned char *ptr, request[500], resource[500]; int fd, length; length = recv_line(sockfd, request); printf("Got request from %s:%d \"%s\"\n", inet_ntoa(client_addr_ptr->sin_addr), ntohs(client_addr_ptr->sin_port), request); ptr = strstr(request, " HTTP/"); if(ptr == NULL) { printf(" NOT HTTP!\n"); } else { *ptr = 0; ptr = NULL; if(strncmp(request, "GET ", 4) == 0) ptr = request+4; if(strncmp(request, "HEAD ", 5) == 0) ptr = request+5; if(ptr == NULL) { printf("\tUNKNOWN REQUEST!\n"); } else { if (ptr[strlen(ptr) - 1] == '/') strcat(ptr, "index.html"); strcpy(resource, WEBROOT); strcat(resource, ptr); fd = open(resource, O_RDONLY, 0); printf("\tOpening '%s'\t", resource); if(fd == -1) { printf(" 404 Not Found\n"); send_string(sockfd, "HTTP/1.0 404 NOT FOUND\r\n"); send_string(sockfd, "Server: Tiny webserver\r\n\r\n"); send_string(sockfd, "404 Not Found"); send_string(sockfd, "

URL not found

\r\n"); } else { printf(" 200 OK\n"); send_string(sockfd, "HTTP/1.0 200 OK\r\n"); send_string(sockfd, "Server: Tiny webserver\r\n\r\n"); if(ptr == request + 4) { if((length = get_file_size(fd)) == -1) fatal("getting resource file size"); if((ptr = (unsigned char *) malloc(length)) == NULL) fatal("allocating memory for reading resource"); read(fd, ptr, length); send(sockfd, ptr, length, 0); free(ptr); } close(fd); } } } shutdown(sockfd, SHUT_RDWR); } // Compile: gcc -o tinyweb tinyweb.c // Run: sudo ./tinyweb // Test: curl http://localhost/index.html ``` -------------------------------- ### C: Demonstrate Memory Segments and Addresses Source: https://context7.com/intere/hacking/llms.txt Illustrates how variables are allocated in different memory segments (data, BSS, heap, stack) and displays their memory addresses. It requires standard C libraries like stdio.h and stdlib.h. ```c #include #include int global_var; // BSS segment (uninitialized) int global_initialized_var = 5; // Data segment (initialized) void function() { int stack_var; printf("function's stack_var at 0x%08x\n", &stack_var); } int main() { int stack_var; static int static_initialized_var = 5; // Data segment static int static_var; // BSS segment int *heap_var_ptr; heap_var_ptr = (int *) malloc(4); // Heap segment // Data segment variables printf("global_initialized_var @ 0x%08x\n", &global_initialized_var); printf("static_initialized_var @ 0x%08x\n", &static_initialized_var); // BSS segment variables printf("static_var @ 0x%08x\n", &static_var); printf("global_var @ 0x%08x\n", &global_var); // Heap segment printf("heap_var @ 0x%08x\n", heap_var_ptr); // Stack segment printf("stack_var @ 0x%08x\n", &stack_var); function(); free(heap_var_ptr); return 0; } // Compile and run: // gcc -o memory_segments memory_segments.c // ./memory_segments ``` -------------------------------- ### Format String Vulnerability Demo in C Source: https://context7.com/intere/hacking/llms.txt Demonstrates the difference between safe and vulnerable printf usage in C. It highlights how user-controlled input can be exploited as a format string, leading to potential information disclosure or crashes. Compile with 'gcc -o fmt_vuln fmt_vuln.c'. ```c #include #include #include int main(int argc, char *argv[]) { char text[1024]; static int test_val = -72; if(argc < 2) { printf("Usage: %s \n", argv[0]); exit(0); } strcpy(text, argv[1]); // Safe: format string is constant, user input as argument printf("The right way to print user-controlled input:\n"); printf("%s", text); // Vulnerable: user input used directly as format string printf("\nThe wrong way to print user-controlled input:\n"); printf(text); // VULNERABLE - allows format string attacks printf("\n"); printf("[*] test_val @ 0x%08x = %d 0x%08x\n", &test_val, test_val, test_val); exit(0); } // Compile: gcc -o fmt_vuln fmt_vuln.c // Safe usage: ./fmt_vuln "Hello World" // Format attack demo: ./fmt_vuln "AAAA%08x.%08x.%08x.%08x" ``` -------------------------------- ### Note-Taking System with File I/O and User IDs in C Source: https://context7.com/intere/hacking/llms.txt A C program that implements a note storage system. It demonstrates file operations, user authentication using UID, and data persistence by writing notes to a file. Compile with 'gcc -o notetaker notetaker.c'. ```c // notetaker.c - Write notes to file with user ID #include #include #include #include #include #include "hacking.h" int main(int argc, char *argv[]) { int userid, fd; char *buffer, *datafile; buffer = (char *) ec_malloc(100); datafile = (char *) ec_malloc(20); strcpy(datafile, "/var/notes"); if(argc < 2) { printf("Usage: %s \n", argv[0], datafile); exit(0); } strcpy(buffer, argv[1]); printf("[DEBUG] buffer @ %p: '%s'\n", buffer, buffer); printf("[DEBUG] datafile @ %p: '%s'\n", datafile, datafile); fd = open(datafile, O_WRONLY|O_CREAT|O_APPEND, S_IRUSR|S_IWUSR); if(fd == -1) fatal("in main() while opening file"); printf("[DEBUG] file descriptor is %d\n", fd); userid = getuid(); if(write(fd, &userid, 4) == -1) fatal("in main() while writing userid to file"); write(fd, "\n", 1); if(write(fd, buffer, strlen(buffer)) == -1) fatal("in main() while writing buffer to file"); write(fd, "\n", 1); if(close(fd) == -1) fatal("in main() while closing file"); printf("Note has been saved.\n"); free(buffer); free(datafile); return 0; } // Compile: gcc -o notetaker notetaker.c // Usage: ./notetaker "This is my note" ``` -------------------------------- ### Note Search System in C Source: https://context7.com/intere/hacking/llms.txt A C program designed to search and display notes belonging to the current user from a file. It supports optional keyword filtering for more specific searches. Compile with 'gcc -o notesearch notesearch.c'. ```c // notesearch.c - Search and display user's notes #include #include #include #include #include "hacking.h" #define FILENAME "/var/notes" int find_user_note(int fd, int user_uid) { int note_uid=-1; unsigned char byte; int length; while(note_uid != user_uid) { if(read(fd, ¬e_uid, 4) != 4) return -1; if(read(fd, &byte, 1) != 1) return -1; byte = length = 0; while(byte != '\n') { if(read(fd, &byte, 1) != 1) return -1; length++; } } lseek(fd, length * -1, SEEK_CUR); printf("[DEBUG] found a %d byte note for user id %d\n", length, note_uid); return length; } int search_note(char *note, char *keyword) { int i, keyword_length, match=0; keyword_length = strlen(keyword); if(keyword_length == 0) return 1; for(i=0; i < strlen(note); i++) { if(note[i] == keyword[match]) match++; else { if(note[i] == keyword[0]) match = 1; else match = 0; } if(match == keyword_length) return 1; } return 0; } int print_notes(int fd, int uid, char *searchstring) { int note_length; char byte=0, note_buffer[100]; note_length = find_user_note(fd, uid); if(note_length == -1) return 0; read(fd, note_buffer, note_length); note_buffer[note_length] = 0; if(search_note(note_buffer, searchstring)) printf(note_buffer); return 1; } int main(int argc, char *argv[]) { int userid, printing=1, fd; char searchstring[100]; if(argc > 1) strcpy(searchstring, argv[1]); else searchstring[0] = 0; userid = getuid(); fd = open(FILENAME, O_RDONLY); if(fd == -1) fatal("in main() while opening file for reading"); while(printing) printing = print_notes(fd, userid, searchstring); printf("-------[ end of note data ]-------\n"); close(fd); return 0; } // Compile: gcc -o notesearch notesearch.c // Usage: ./notesearch [keyword] ``` -------------------------------- ### C: Simple TCP Server with Socket Operations Source: https://context7.com/intere/hacking/llms.txt Implements a basic TCP server that demonstrates socket creation, binding, listening, and accepting connections. It also includes data reception and hex dumping of received data. Requires 'hacking.h' for the 'fatal' function and 'dump' utility. ```c #include #include #include #include #include #include #include "hacking.h" #define PORT 7890 int main(void) { int sockfd, new_sockfd; struct sockaddr_in host_addr, client_addr; socklen_t sin_size; int recv_length=1, yes=1; char buffer[1024]; if ((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1) fatal("in socket"); if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) fatal("setting socket option SO_REUSEADDR"); host_addr.sin_family = AF_INET; host_addr.sin_port = htons(PORT); host_addr.sin_addr.s_addr = INADDR_ANY; memset(&(host_addr.sin_zero), '\0', 8); if (bind(sockfd, (struct sockaddr *)&host_addr, sizeof(struct sockaddr)) == -1) fatal("binding to socket"); if (listen(sockfd, 5) == -1) fatal("listening on socket"); while(1) { sin_size = sizeof(struct sockaddr_in); new_sockfd = accept(sockfd, (struct sockaddr *)&client_addr, &sin_size); if(new_sockfd == -1) fatal("accepting connection"); printf("server: got connection from %s port %d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); send(new_sockfd, "Hello World!\n", 13, 0); recv_length = recv(new_sockfd, &buffer, 1024, 0); while(recv_length > 0) { printf("RECV: %d bytes\n", recv_length); dump(buffer, recv_length); recv_length = recv(new_sockfd, &buffer, 1024, 0); } close(new_sockfd); } return 0; } // Compile: gcc -o simple_server simple_server.c // Run: ./simple_server // Test: nc localhost 7890 ``` -------------------------------- ### Dictionary-Based Password Cracker using C Source: https://context7.com/intere/hacking/llms.txt This C program performs a dictionary-based password attack against Unix crypt() hashes. It takes a wordlist file and a password hash as input, iterates through the wordlist, and attempts to find a matching plaintext password. Dependencies include standard C libraries and the crypt library. ```c #define _XOPEN_SOURCE #include #include #include #include void barf(char *message, char *extra) { printf(message, extra); exit(1); } int main(int argc, char *argv[]) { FILE *wordlist; char *hash, word[30], salt[3]; if(argc < 3) barf("Usage: %s \n", argv[0]); strncpy(salt, argv[2], 2); // First 2 bytes of hash are the salt salt[2] = '\0'; printf("Salt value is '%s'\n", salt); if((wordlist = fopen(argv[1], "r")) == NULL) barf("Fatal: couldn't open the file '%s'.\n", argv[1]); while(fgets(word, 30, wordlist) != NULL) { word[strlen(word)-1] = '\0'; // Remove newline hash = crypt(word, salt); printf("trying word: %-30s ==> %15s\n", word, hash); if(strcmp(hash, argv[2]) == 0) { printf("The hash \"%s\" is from the ", argv[2]); printf("plaintext password \"%s\".\n", word); fclose(wordlist); exit(0); } } printf("Couldn't find the plaintext password in the supplied wordlist.\n"); fclose(wordlist); return 1; } // Compile: gcc -o crypt_crack crypt_crack.c -lcrypt // Create test hash: perl -e 'print crypt("test", "XX") . "\n"' // Usage: ./crypt_crack /usr/share/dict/words XXq2wKiyI43A2 ``` -------------------------------- ### Packet Sniffer with Protocol Decoding (C) Source: https://context7.com/intere/hacking/llms.txt Captures network packets using libpcap and decodes Ethernet, IP, and TCP headers. It displays packet information including source/destination MAC addresses, IP addresses, and TCP flags. Requires libpcap library for compilation and execution. ```c #include #include "hacking.h" #include "hacking-network.h" void pcap_fatal(const char *failed_in, const char *errbuf) { printf("Fatal Error in %s: %s\n", failed_in, errbuf); exit(1); } void decode_ethernet(const u_char *header_start) { int i; const struct ether_hdr *ethernet_header; ethernet_header = (const struct ether_hdr *)header_start; printf("[[ Layer 2 :: Ethernet Header ]]\n"); printf("[ Source: %02x", ethernet_header->ether_src_addr[0]); for(i=1; i < ETHER_ADDR_LEN; i++) printf(":%02x", ethernet_header->ether_src_addr[i]); printf("\tDest: %02x", ethernet_header->ether_dest_addr[0]); for(i=1; i < ETHER_ADDR_LEN; i++) printf(":%02x", ethernet_header->ether_dest_addr[i]); printf("\tType: %hu ]\n", ethernet_header->ether_type); } void decode_ip(const u_char *header_start) { const struct ip_hdr *ip_header; ip_header = (const struct ip_hdr *)header_start; printf("\t(( Layer 3 ::: IP Header ))\n"); printf("\t( Source: %s\t", inet_ntoa(ip_header->ip_src_addr)); printf("Dest: %s )\n", inet_ntoa(ip_header->ip_dest_addr)); printf("\t( Type: %u\tID: %hu\tLength: %hu )\n", (u_int)ip_header->ip_type, ntohs(ip_header->ip_id), ntohs(ip_header->ip_len)); } u_int decode_tcp(const u_char *header_start) { u_int header_size; const struct tcp_hdr *tcp_header; tcp_header = (const struct tcp_hdr *)header_start; header_size = 4 * tcp_header->tcp_offset; printf("\t\t{{ Layer 4 :::: TCP Header }}\n"); printf("\t\t{ Src Port: %hu\tDest Port: %hu }\n", ntohs(tcp_header->tcp_src_port), ntohs(tcp_header->tcp_dest_port)); printf("\t\t{ Seq #: %u\tAck #: %u }\n", ntohl(tcp_header->tcp_seq), ntohl(tcp_header->tcp_ack)); printf("\t\t{ Header Size: %u\tFlags: ", header_size); if(tcp_header->tcp_flags & TCP_FIN) printf("FIN "); if(tcp_header->tcp_flags & TCP_SYN) printf("SYN "); if(tcp_header->tcp_flags & TCP_RST) printf("RST "); if(tcp_header->tcp_flags & TCP_PUSH) printf("PUSH "); if(tcp_header->tcp_flags & TCP_ACK) printf("ACK "); if(tcp_header->tcp_flags & TCP_URG) printf("URG "); printf(" }\n"); return header_size; } void caught_packet(u_char *user_args, const struct pcap_pkthdr *cap_header, const u_char *packet) { int tcp_header_length, total_header_size, pkt_data_len; u_char *pkt_data; printf("==== Got a %d byte packet ====\n", cap_header->len); decode_ethernet(packet); decode_ip(packet+ETHER_HDR_LEN); tcp_header_length = decode_tcp(packet+ETHER_HDR_LEN+sizeof(struct ip_hdr)); total_header_size = ETHER_HDR_LEN+sizeof(struct ip_hdr)+tcp_header_length; pkt_data = (u_char *)packet + total_header_size; pkt_data_len = cap_header->len - total_header_size; if(pkt_data_len > 0) { printf("\t\t\t%u bytes of packet data\n", pkt_data_len); dump(pkt_data, pkt_data_len); } else printf("\t\t\tNo Packet Data\n"); } int main() { char errbuf[PCAP_ERRBUF_SIZE]; char *device; pcap_t *pcap_handle; device = pcap_lookupdev(errbuf); if(device == NULL) pcap_fatal("pcap_lookupdev", errbuf); printf("Sniffing on device %s\n", device); pcap_handle = pcap_open_live(device, 4096, 1, 0, errbuf); if(pcap_handle == NULL) pcap_fatal("pcap_open_live", errbuf); pcap_loop(pcap_handle, 3, caught_packet, NULL); pcap_close(pcap_handle); return 0; } // Compile: gcc -o decode_sniff decode_sniff.c -lpcap // Run: sudo ./decode_sniff ``` -------------------------------- ### Core Utility Functions in C (hacking.h) Source: https://context7.com/intere/hacking/llms.txt Provides essential utility functions for error handling, memory allocation with checks, and hexadecimal memory dumping. These functions are crucial for debugging and robust program execution in C. ```c #include #include #include // Display an error message and exit the program void fatal(char *message) { char error_message[100]; strcpy(error_message, "[!!] Fatal Error "); strncat(error_message, message, 83); perror(error_message); exit(-1); } // Error-checked malloc wrapper - exits on allocation failure void *ec_malloc(unsigned int size) { void *ptr; ptr = malloc(size); if(ptr == NULL) fatal("in ec_malloc() on memory allocation"); return ptr; } // Dump raw memory in hex and printable ASCII format void dump(const unsigned char *data_buffer, const unsigned int length) { unsigned char byte; unsigned int i, j; for(i=0; i < length; i++) { byte = data_buffer[i]; printf("%02x ", data_buffer[i]); if(((i%16)==15) || (i==length-1)) { for(j=0; j < 15-(i%16); j++) printf(" "); printf("| "); for(j=(i-(i%16)); j <= i; j++) { byte = data_buffer[j]; if((byte > 31) && (byte < 127)) printf("%c", byte); else printf("."); } printf("\n"); } } } ``` -------------------------------- ### TCP/IP Protocol Structures in C Source: https://context7.com/intere/hacking/llms.txt Defines C structures that map to Ethernet, IP, and TCP headers. These structures are used for inspecting and constructing network packets in C. ```c // Ethernet header structure (14 bytes) #define ETHER_ADDR_LEN 6 #define ETHER_HDR_LEN 14 struct ether_hdr { unsigned char ether_dest_addr[ETHER_ADDR_LEN]; unsigned char ether_src_addr[ETHER_ADDR_LEN]; unsigned short ether_type; }; // IP header structure struct ip_hdr { unsigned char ip_version_and_header_length; unsigned char ip_tos; unsigned short ip_len; unsigned short ip_id; unsigned short ip_frag_offset; unsigned char ip_ttl; unsigned char ip_type; unsigned short ip_checksum; unsigned int ip_src_addr; unsigned int ip_dest_addr; }; // TCP header structure with flag definitions struct tcp_hdr { unsigned short tcp_src_port; unsigned short tcp_dest_port; unsigned int tcp_seq; unsigned int tcp_ack; unsigned char reserved:4; unsigned char tcp_offset:4; unsigned char tcp_flags; #define TCP_FIN 0x01 #define TCP_SYN 0x02 #define TCP_RST 0x04 #define TCP_PUSH 0x08 #define TCP_ACK 0x10 #define TCP_URG 0x20 unsigned short tcp_window; unsigned short tcp_checksum; unsigned short tcp_urgent; }; ``` -------------------------------- ### Network Utility Functions in C (hacking-network.h) Source: https://context7.com/intere/hacking/llms.txt Provides reliable socket communication functions for sending strings and receiving lines terminated by \r\n. These are essential for building network clients and servers in C. ```c // Send all bytes of a string reliably over a socket // Returns 1 on success, 0 on failure int send_string(int sockfd, unsigned char *buffer) { int sent_bytes, bytes_to_send; bytes_to_send = strlen(buffer); while(bytes_to_send > 0) { sent_bytes = send(sockfd, buffer, bytes_to_send, 0); if(sent_bytes == -1) return 0; bytes_to_send -= sent_bytes; buffer += sent_bytes; } return 1; } // Receive a line terminated by \r\n from socket // Returns the size of the line (without EOL bytes) int recv_line(int sockfd, unsigned char *dest_buffer) { #define EOL "\r\n" #define EOL_SIZE 2 unsigned char *ptr; int eol_matched = 0; ptr = dest_buffer; while(recv(sockfd, ptr, 1, 0) == 1) { if(*ptr == EOL[eol_matched]) { eol_matched++; if(eol_matched == EOL_SIZE) { *(ptr+1-EOL_SIZE) = '\0'; return strlen(dest_buffer); } } else { eol_matched = 0; } ptr++; } return 0; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.