C Programming: Library Creation, Encryption, and System Call Hijacking

The provided texts encompass diverse topics in programming and computer science. One excerpt focuses on creating a SOCKS version 4 client in C to connect to the Tor network, detailing packet creation, data transmission/reception, and proxy traversal. Another segment explores XOR encryption, demonstrating its implementation in C for single-character encryption/decryption. A further discussion involves creating an encryption library using a modified ARC4 algorithm. An additional piece elucidates Linux file system permissions, explaining read, write, and execute permissions alongside their numeric representations. Finally, a text introduces creating a safe string library in C to avoid buffer overflows and memory corruption issues when handling strings, and the last text describes the use of functions to hijack connections made through the tour network by creating shared libraries and altering prioritization order.

Source Code Deep Dive: Study Guide

I. Quiz

Answer each question in 2-3 sentences.

  1. What is the difference between a system call and a library call, and how can you determine which one is being used?
  2. What is the purpose of the htons() function, and why is it needed when working with network addresses?
  3. Explain the role of a makefile and the benefits of using one when compiling C code.
  4. What are the three essential elements needed to establish a TCP connection, and what specific steps are involved in configuring these elements?
  5. Explain the concept of a “predicate” in programming.
  6. How does the XOR operation work, and why is it useful for basic encryption?
  7. Why is it important to zero out buffers in the example code provided?
  8. What is a “type definition” in C programming, and what is its purpose?
  9. Explain the purpose of the assert() function and how it can be used for debugging.
  10. Explain what LD_PRELOAD does and how it can be used to override existing function calls.

II. Quiz Answer Key

  1. A system call is a direct request to the operating system kernel, while a library call is a function provided by a library that may eventually use system calls. To determine which one is being used, you can consult the manual pages using man 2 for system calls and man 3 for library calls.
  2. The htons() function converts a host’s byte order to network byte order. This is necessary because different systems use different byte orders, and network communication requires a consistent order.
  3. A makefile automates the build process by defining dependencies and commands for compiling and linking code. This simplifies the compilation process, especially for projects with multiple source files.
  4. The three essential elements are the address family, the port number, and the IP address. These elements must be configured in a socket address structure before initializing the connection with the connect() command.
  5. A predicate is a function or operation that returns a boolean value, indicating whether a certain condition is true or false.
  6. XOR (exclusive OR) is a bitwise operation that returns 1 if the input bits are different and 0 if they are the same. It’s used for simple encryption because applying the same key twice decrypts the data.
  7. Zeroing out buffers ensures that they are initialized with a known state, preventing potential issues with leftover data or undefined behavior.
  8. A type definition creates an alias for an existing data type, making the code more readable and easier to maintain.
  9. The assert() function checks if a given condition is true, and if it’s false, the program terminates with an error message. It’s used to catch programming errors and ensure code integrity.
  10. LD_PRELOAD is an environment variable that specifies shared libraries to load before any others. It can be used to intercept and replace function calls, effectively overriding existing system behavior.

III. Essay Questions

  1. Discuss the security implications of using a simple XOR encryption method, and explain the limitations of its cryptographic strength.
  2. Analyze the structure of a SOCKS version 4 client and its role in connecting to the Tor network.
  3. Elaborate on the benefits and drawbacks of using the getrandom() system call for generating cryptographically secure random numbers.
  4. Explain the purpose of “whitewashing” the RC4 keystream, and how it enhances the security of RC4 encryption.
  5. Explain the advantages and disadvantages of manually managing strings compared to using standard C functions, highlighting the security implications of both approaches.

IV. Glossary of Key Terms

  • System Call: A request made by a program to the operating system kernel to perform a specific task.
  • Library Call: A function provided by a library that may eventually use system calls.
  • Socket: An endpoint of a two-way communication link between two programs running on the network.
  • TCP (Transmission Control Protocol): A connection-oriented protocol that provides reliable, ordered, and error-checked delivery of data between applications.
  • SOCKS (Socket Secure): An Internet protocol that routes network packets between a client and server through a proxy server.
  • Tor (The Onion Router): A free and open-source software for enabling anonymous communication.
  • Proxy Server: A server that acts as an intermediary between a client seeking resources and a server providing those resources.
  • Makefile: A file containing a set of directives used by the make utility to automate the compilation and linking of software.
  • Byte Order (Endianness): The order in which bytes of a multi-byte data type are stored in memory.
  • Network Byte Order: A standardized byte order used for network communication, typically big-endian.
  • Host Byte Order: The byte order used by the host system, which may be big-endian or little-endian.
  • htons(): A function that converts a 16-bit host byte order to network byte order.
  • AF_INET (Address Family Internet): An address family that is used to designate the type of addresses that the socket can communicate with (IPv4).
  • SOCK_STREAM: A socket type that provides sequenced, reliable, two-way, connection-based byte streams.
  • Predicate: A function or operation that returns a boolean value (true or false).
  • XOR (Exclusive OR): A bitwise operation that returns 1 if the input bits are different and 0 if they are the same.
  • Ciphertext: Encrypted data.
  • Cleartext: Unencrypted data.
  • Type Definition: A statement that creates an alias for an existing data type.
  • Assert(): A macro that tests a given condition, and if the condition is false, the program terminates.
  • Maloc(): A function that allocates a block of memory dynamically.
  • LD_PRELOAD: An environment variable that specifies shared libraries to load before any others.
  • RC4 (Rivest Cipher 4): A stream cipher widely used in software applications and protocols.
  • Keystream: A sequence of pseudo-random bytes used to encrypt or decrypt data.
  • Whitewashing: The process of discarding initial keystream bytes in RC4 to mitigate certain statistical weaknesses.
  • Entropy: A measure of the randomness or unpredictability of data.
  • getrandom(): A system call that retrieves random bytes from the kernel’s entropy pool.
  • DL_SIM: A flag in some C compilers, like GCC, that is used to link a dynamically loaded library, and tells the linker that all symbols in the library should be considered defined, even if they are not explicitly used.
  • LD_PRELOAD: An environment variable used to specify shared libraries that should be loaded before others.
  • Change Mod: (chmod) the command for altering permissions on a Unix and Linux system.
  • Change Own (chown) the command which changes the owner of a specific file in Unix and Linux system.

Tor Tunneling Tool: Development and Security Briefing

Okay, here’s a detailed briefing document summarizing the key themes and ideas from the provided source material.

Briefing Document: Tor Proxy Tool Development & Related Concepts

Overview:

The sources document the development process of a tool (“talize”) designed to tunnel network connections through the Tor network. The materials also touch on foundational concepts related to networking (system calls, library calls, TCP connections), security (encryption with XOR, file permissions in Linux), and C programming (dynamic linking, shared libraries, memory management).

Main Themes & Important Ideas:

  1. System Call Interception for Tor Tunneling:
  • The core idea is to intercept system calls (specifically, connect) made by other applications and redirect the connections through a Tor proxy. This allows any application to utilize the Tor network without explicit configuration within the application itself.
  • The tool uses LD_PRELOAD to inject a shared library that overrides the standard connect function.
  • “You remember I want to be able to do something like talize and then run any [Music] command like curve against some IP address and then I want to in intercept the connection I want to run this command as is but I want to intercept the con the connection that the actual program does and run my code instead so it tunnels through the tour Network any program that we want to run…”
  1. SOCKS4 Proxy Implementation:
  • The tool establishes a TCP connection to a SOCKS4 proxy server (typically running on localhost at port 9050 when using Tor).
  • The source code shows the creation of a socket, setting the socket address family to AF_INET, specifying the proxy port, and using the connect system call to connect to the proxy.
  • “So now we have successfully created our TCP connection towards the proxy server and the next step is to create the uh proxy request packet according to this structure that we created before.”
  • The source code shows the creation of a socket using socket(SOCK_INET, SOCK_STREAM, 0).
  1. C Programming Techniques & Challenges:
  • The source code demonstrates various C programming techniques, including:
  • System calls (e.g., socket, connect, close, open, read, write, getrandom).
  • Library calls (e.g., htons, inet_addr, strlen, malloc, free, perror, sprintf, snprintf, memset).
  • Pointers, structures, type definitions (typedef).
  • Dynamic memory allocation (malloc, free).
  • String manipulation.
  • Function pointers (for intercepting system calls).
  • Shared libraries (.so files).
  • Bitwise operations.
  • Challenges encountered during development include:
  • Compiler errors and warnings (due to type mismatches, incorrect syntax, missing include files, etc.).
  • Memory management issues (leaks, segmentation faults).
  • Debugging dynamic linking issues.
  • Getting terminal settings correct for password input (disabling echo).
  • Troubleshooting network connectivity problems.
  1. Security Considerations:
  • The material briefly mentions the importance of using cryptographically secure random number generators (getrandom) for security-sensitive tasks.
  • The use of XOR encryption is described as a simple demonstration and not suitable for real-world security.
  • The need to “whitewash” the initial state of RC4 is also mentioned to mitigate potential weaknesses.
  • File permissions and ownership within a Linux environment were mentioned.
  • “This is a very basic form of encryption that uh is only for demonstrational purposes it’s quite easy to crack with today’s Technologies and computer power however it’s a good example on how to use exor…”
  1. Dynamic Linking and LD_PRELOAD:
  • The tool relies heavily on dynamic linking, using LD_PRELOAD to inject a custom shared library that overrides the standard connect system call. This allows the tool to transparently intercept and redirect connections made by other applications.
  • The source contains instructions on setting the LD_PRELOAD environment variable.
  • “So we need to send everything that’s on the right of this toriz and there is a way to access all the arguments at the same time and I I think it is done like this okay so first we export the LD preload and point it towards our shared library then we do the dollar and I think it’s the at sign which will run all the arguments to this uh script…”
  1. Practical Implementation of RC4 Encryption:
  • A significant portion of the material details the implementation of the RC4 encryption algorithm.
  • The code includes functions for:
  • Initialization (Arc4Init).
  • Key stream generation (Arc4Byte).
  • Encryption/Decryption (Arc4Encrypt).
  1. Safe String Handling:
  • The need for safe string handling is emphasized to prevent buffer overflows and other security vulnerabilities.
  • The material describes a custom string library that provides functions for:
  • Initialization.
  • Concatenation (automatically reallocating memory as needed).
  • The source shows implementations of custom length and copy functions for increased control over string manipulation.
  1. File Permissions in Linux:
  • The sources include an explanation of file permissions in Linux using chmod.
  • This includes the meaning of the numeric representation (e.g., 755) and its relationship to read, write, and execute permissions for the owner, group, and others.
  • “What does this 755 mean in the detail this and more we’re going to talk about today when we are discussing Linux file system [Music] security…”

Quotes from Original Sources:

  • “is a system call that’s why how do you know if it’s a system call or a library call try a library call first three if you don’t get a hit or if you get a hit that doesn’t seem right try the uh the two okay so we need sis socket.”
  • “…our program works fine this far but at the moment it’s just a proxy server client it’s not doing what we intended it to do from the beginning…that is what I want to do and that is the next step in this process…”
  • “If you like this episode and want to see the continuation or other stuff in this Channel please uh subscribe to this Channel and hit the like button if you think I deserve it…”
  • “Today you have learned about Linux file system security that there are three parts to it the file permissions targets and the change mode command…”

In Summary:

The sources provide a comprehensive look at the development of a Tor tunneling tool, highlighting both the network programming aspects (SOCKS4 proxy, system call interception) and the C programming techniques required to build such a tool. The material also emphasizes the importance of secure coding practices, including proper memory management, random number generation, and safe string handling. Furthermore, background context for other core security topics such as encryption and file permissions are provided.

C System Calls, Sockets, Encryption, and LD_PRELOAD

### What is a system call, and how do you identify one compared to a library call?

A system call is a request to the operating system’s kernel to perform a privileged operation. To differentiate: first, try a library call using `man 3 <function_name>`. If that doesn’t yield relevant information, try `man 2 <function_name>` as system calls are documented in section 2 of the manual pages.

### What are the essential steps to create a TCP connection to a proxy server using C?

1. **Create a Socket:** Use the `socket()` function to obtain a socket file descriptor. Specify the address family (e.g., `AF_INET`), socket type (`SOCK_STREAM` for TCP), and protocol (0 for the default).

2. **Prepare the Socket Address:** Create a `sockaddr_in` structure. Set the address family (`sin_family` to `AF_INET`), the port number (`sin_port` using `htons()` to convert to network byte order), and the IP address (`sin_addr.s_addr` using `inet_addr()`).

3. **Connect:** Call the `connect()` function, passing the socket file descriptor, a pointer to the `sockaddr_in` structure (cast to `sockaddr*`), and the size of the structure. Check the return value; 0 indicates success, and -1 indicates an error.

### Explain the purpose of function declarations in C, and why they might be used.

Function declarations (or prototypes) tell the compiler about the existence, return type, and arguments of a function before it’s actually defined. They allow you to call a function that’s defined later in the same file or in a different file. While not strictly required if a function is defined before it’s called, they improve code organization and readability.

### What is a predicate and how are they used within the given context?

A predicate is a function or operation that returns a boolean value (true or false). In C, this is typically represented by an integer, where 0 is false and any non-zero value is true. In the context of proxy traversal, a predicate might check the value of a response code (like the CD value) to determine if the proxy connection was successful.

### How does the XOR operation work, and why is it useful for simple encryption?

The XOR (exclusive OR) operation compares two bits. If the bits are different (one is 0 and the other is 1), the result is 1. If the bits are the same (both 0 or both 1), the result is 0. XOR is used for simple encryption because applying the same XOR key twice decrypts the data. `(A XOR Key) XOR Key = A`.

### How does the RC4 encryption algorithm work?

The RC4 algorithm involves three main steps:

1. **Initialization:** An array ‘S’ of 256 bytes is filled with values 0 to 255. Then, using a key (typically 8 to 2048 bits), ‘S’ is scrambled based on the key, using two index variables ‘i’ and ‘j’.

2. **Key-stream Generation:** The algorithm then enters a loop where ‘i’ and ‘j’ are continuously updated, and two bytes in ‘S’ are swapped. The value of `S[S[i] + S[j]]` is XORed with the plaintext to produce the ciphertext.

3. **Encryption/Decryption:** The keystream is XORed with the plaintext to encrypt, and the same keystream is XORed with the ciphertext to decrypt.

### What security concern is addressed by “whitewashing” the RC4 algorithm, and how is it implemented in the code?

A known weakness of RC4 is that the initial bytes of the keystream can be statistically biased. “Whitewashing” involves discarding the first several million bytes of keystream after the initialization to mitigate this bias. It is implemented by calling the `Arc4Byte()` function many times (e.g., 500 million times) after the initialization.

### How can `LD_PRELOAD` be used to intercept function calls and redirect network traffic through Tor?

`LD_PRELOAD` is an environment variable that lists shared libraries to be loaded before others when a program is started. By creating a shared library that intercepts network-related functions like `connect()`, you can replace the original functions with your own. This allows you to modify the behavior of network calls, redirecting traffic through the Tor network, while the original program remains unchanged.

Socket Programming Essentials

The sources provide the following information regarding sockets:

  • A socket is initialized using the socket command. The syntax includes sock_eynut and sock_stream for a TCP connection. If the socket initialization fails (less than zero), an error message is printed using the perror command.
  • A structure called sock address in is needed to specify IP addresses. The s family needs to be set to AF IET, the Sin port using H ton s for network byte order, and the sin address using inut address.
  • The connect command is used to initialize the actual connection. It references the socket and the structure and requires an explicit type casting to Sock address struct. The connect command should return a zero if the connection/binding succeeds. Otherwise, it returns a -1.
  • The close command is used to close down the connection.
  • When creating TCP client, functions such as sockets to initialize the sockets, connect, close AG tone s, and in address are needed. The include files required are sys/socket.h, netinet/in.h, and arpa/inet.h.
  • The dup2 system call can create a new file descriptor that duplicates an existing one, allowing for piping data between sockets.

C Library Calls: System Calls, Shared Libraries, and Interception

The sources mention library calls in the context of C programming, particularly in relation to system calls and shared libraries. Here’s a breakdown:

  • Distinction from System Calls: The source draws a distinction between library calls and system calls, noting that to determine whether a function is a system call or a library call, one should first check the manual pages section 3 (man 3) and if it does not seem right, try section 2 (man 2).
  • Wrappers for System Calls: Libraries can contain wrappers for system calls, such as the connect function.
  • Shared Libraries: The source explains the concept of shared libraries, which contain code that can be used by multiple programs, avoiding duplication. Instead of every program containing its own copy of functions like printf, these functions are stored in a central repository and accessed when needed.
  • Function Hooking/Interception: The source describes a technique to intercept library calls by creating a shared library with a function of the same name and signature as the library call you want to intercept. By preloading this library, you can ensure that your version of the function is called instead of the original. The original function can still be accessed using dlsym.
  • Creating a Shared Library: To create a shared library, specific compiler flags are required. In the makefile example, the flags -fPIC, -shared, and -Wl,-soname are used.
  • Using a Shared Library: To use a created shared library, it can be preloaded using the LD_PRELOAD environment variable. This can be done by creating a bash script that exports LD_PRELOAD to the path of the shared library. After setting the environment variable, the script executes the desired command, and then unsets the LD_PRELOAD variable.
  • Safe String Library: The source discusses the creation of a safe string library to prevent buffer overflows and other security issues related to string manipulation in C.

Type Casting: Uses and Applications

Type casting is mentioned in the sources in several contexts, particularly in C programming. Here’s a breakdown:

  • General Use: Type casting is used to convert a variable or expression from one data type to another. This is often necessary when a function expects a specific type, but the provided argument is of a different type.
  • Explicit Type Casting: The source demonstrates explicit type casting using the syntax (type)variable. For example, (Sock address struct*) is used to cast a pointer to a sockaddr_in structure to a Sock address struct* when calling the connect function. Another example is (int8*) to cast a string to a specific type for a function argument.
  • Socket Programming: In socket programming, type casting is essential when dealing with network addresses. The connect function, for instance, requires a Sock address struct* argument, so you may need to cast your address structure to this type.
  • Pointer Conversions: Type casting is often used when converting between different pointer types. For instance, a void* pointer, which is a generic pointer type, might need to be cast to a specific type like char* before being dereferenced.
  • Addressing Compiler Warnings: Type casting can be used to suppress compiler warnings related to incompatible pointer types or different signedness. For example, casting a char* to int8*. However, the source notes that it may be better to change the variable types to regular strings.
  • Volatile Type Cast: When using memory locations, you can use type casting to tell the compiler to not optimize a segment of code. This is done using the syntax: (volatile int8*).

C Memory Allocation: Dynamic, Safe, and Networked

Memory allocation is discussed in the sources in the context of C programming, particularly when working with strings, structures, and network operations. Here’s a breakdown:

  • Dynamic Memory Allocation: The source highlights the use of malloc to dynamically allocate memory on the heap. This is essential when the size of the memory required is not known at compile time or when you need memory that persists beyond the scope of a function. For example, when creating strings or structures, malloc is used to allocate the necessary space in memory.
  • Memory Allocation Size: When using malloc, it’s crucial to allocate the correct amount of memory. This often involves using the sizeof operator to determine the size of a data type or structure. For strings, you need to allocate enough space for the characters plus a null terminator. The source uses size of stct proxy request and size of stct s AR for to allocate memory appropriate to the size of the structure.
  • Checking for Allocation Errors: After calling malloc, it’s important to check if the allocation was successful. If malloc fails, it returns NULL. The code includes assert statements or if clauses to check for NULL pointers and handle allocation errors.
  • realloc for Resizing Memory: The source mentions realloc, which is used to resize a previously allocated block of memory. This is useful when you need to increase or decrease the amount of memory allocated to a string or other data structure.
  • calloc: You can also use calloc, but it wasn’t explicitly in the sources. calloc differs from malloc because it initializes the allocated memory to zero.
  • memcpy for copying memory: memcpy can be used to copy a block of memory from one location to another.
  • memset for initializing memory: memset is used to fill a block of memory with a specific value, often zero. This is useful for initializing buffers or structures before use.
  • free for Deallocating Memory: When you’re finished with dynamically allocated memory, it’s essential to release it using free. This prevents memory leaks and allows the memory to be reused by other parts of the program or the operating system. The source includes examples of freeing allocated memory using free(request) and defining a macro un init of free X.
  • Safe String Library: In the context of creating a safe string library, memory allocation and deallocation are crucial. The source describes how to allocate memory for strings using malloc and realloc, and how to manage the size of the allocated memory to prevent buffer overflows.
  • Variable Length Arrays: The source touches on variable length arrays within structures, where the size of the array is determined at runtime. This allows for flexible memory allocation based on the actual data being stored.
  • Stack vs Heap: The source implicitly refers to the stack when discussing buffer overflows, noting that variables on the stack have limited space, and overflowing them can lead to program crashes. Dynamic memory allocation with malloc occurs on the heap, which is a larger, more flexible memory area.
  • Memory Layout: In network programming, understanding memory layout and byte order is important. The source mentions the need to convert port numbers and IP addresses to network byte order using functions like H ton s and inet_addr. This ensures that the data is interpreted correctly regardless of the system’s architecture.
  • Potential Issues: If memory cannot be allocated, assert P error can be used to handle any potential issues.

C Encryption Libraries: RC4, XOR, and Secure String Handling

The sources discuss the creation of encryption libraries in C, touching upon various aspects from basic encryption principles to more advanced cipher implementations.

Key Concepts and Techniques:

  • XOR Encryption: A basic form of encryption using the XOR operation is explained. The XOR operation is applied to each bit of the data with a key; applying the same operation again with the same key decrypts the data. This method is presented for demonstration purposes and is noted to be easily cracked with modern computing power.
  • RC4 Cipher Implementation: The sources detail the development of an encryption library based on the RC4 algorithm. RC4 is noted as relatively easy to implement but requires careful handling to be secure.
  • The implementation involves creating initialization, encryption, and decryption functions.
  • The library is designed to be used by other C projects, so the core code (arc4.c) doesn’t have a main function, but an example program (example.c) is used for testing.
  • Initialization: The RC4 algorithm’s initialization involves preparing the internal state of the encryption engine based on a key. This includes setting up an array and using a loop to iterate through it.
  • Key Stream Generation: The core of RC4 involves generating a key stream, which is then XORed with the plaintext to produce the ciphertext. The Arc for byte function produces a single byte of the key stream.
  • Encryption and Decryption: In RC4, encryption and decryption are performed using the same operation (XOR with the key stream). Therefore, a single function can be used for both, simplifying the code.
  • Security Considerations:
  • The sources mention concerns about RC4’s security, noting that its output can be distinguishable from random data, potentially allowing attacks.
  • To mitigate these concerns, the implementation includes a “white washing” mechanism that discards the first several million bytes of output to avoid known cracking techniques. This involves generating many bytes using Arc for B and performing a volatile type cast to tell GCC not to optimize it.
  • The importance of using a strong, randomly generated key is emphasized.
  • Library Structure:
  • The encryption library consists of multiple files:
  • arc4.c: Contains the actual code for the RC4 algorithm.
  • arc4.h: Contains the structure definitions, includes, definitions, and macros.
  • example.c: A temporary file with a main function that serves as an example program to try things out.
  • makefile: Contains the instructions to compile the whole thing.
  • The header file (arc4.h) includes necessary definitions and structures, such as the structure representing the internal state of the RC4 encryption engine. This structure typically contains variables like I, J, and an array S.
  • Exporting functions: The keyword export can be defined to ensure that certain functions, like Arc for in it and Arc for encrypt, are accessible from outside the library.
  • Installation: The source outlines how to install a created library, including copying the .so file to the appropriate library directory (e.g. /usr/lib/x86_64-linux-gnu/) and the .h file to the include directory (e.g. /usr/include), and running ldconfig to update the system’s library cache.
  • Safe String Library: The source also discusses the creation of a safe string library to prevent buffer overflows, and a concat function is presented. The length is checked and if needed memory reallocated with realloc, and an M copy function is defined and used.
  • File Encryption: The source describes the structure of an encrypted file including padding bytes, password hashes, and encrypted content.
  • Random Number Generation: For cryptographic operations, it’s crucial to use a secure random number generator. The source mentions using the get random system call with the GRND_RANDOM flag to obtain cryptographically secure random numbers from the entropy pool. The code handles the possibility of the entropy pool being empty and includes a warning message for the user.
  • Key Retrieval: When coding an encryption program, you will need a way to read the encryption key from the command line, and you don’t want to echo the key on the screen. This can be done using functions from the termal.h header.
8 hours of C coding projects: Cyber Security
C Language Full Course in 50 HOURS with Practical (Beginners to Advanced) | 2025 Edition

The Original Text

what’s up guys today we’ll code something really exciting we’re going to be H creating a tool called talyer it’s a command line client for connecting to the tour privacy Network when you run a CLI command for doing a network call for example curl the following thing has happens the connect function is invoked and the uh program establishes a TCP connection to the remote server and then the communication begins but with this tool you’ll be able to put the word talize in front of any command which does a network call taly Will intercept any calls to the connect function and execute our function instead the traffic will be redirected to a local proxy server which is a part of the tour software it will connect to the tour Network and then to the destination server effectively masking your identity and helping you to stay private on the internet and the best thing is coding this is easier than than you might think let’s get on with it okay guys welcome to this episode the first thing we need to do today is we’re going to create our own uh Pro server client so this uh Proxes it uses a protocol named Socks s o ckss and there are two different uh protocol versions version four and version five and the the tour Network and the software supports both these versions version five is a little bit more complicated but version 4 should be very easy to implement and it will be perfect to do it in C so that’s the task of today creating our own client for that sock proxy and use it to connect to the tour Network so how do we start I’m going to start by logging into my code Planet server like this and prepare my screen as I usually do uh today I’m not going to be coding in Naro or VI like I usually do this is a little bigger project a little bit more ambitious could do it in VI even though it’s a big project but uh I’m going to be using um vs code today actually [Music] I’m going to do my wild true command so I don’t accidentally close down my screen window like this um and since I am using a remote server I need to somehow either upload my uh C files and stuff to that server or code remotely in V code somehow and I’m going to be using a tool which is called the sociopath SCP client like this if you want to download sociopath SCP client it’s a tool that uses the SCP protocol which is basically installed on on every server uh to uh upload and download files and subdirectories and there’s also a remote file editing feature that we’re going to use today okay so let’s begin there I have started up the program which looks like this so I connect to my code Planet server and I go to my code folder so on the left side is my local hard disk drive and on the right is uh the files and directories on the server so I’m going to right click and create a new directory which I’m going to call talize this and now I’m going to select the toriz I’m going to right click and I’m going to click open in editor then it’s going to download uh everything in that uh folder which is currently empty but if it were any code files in that folder it would download it to Temporary directory and open it in this code and each time you save or create a file or a directory inside of V code it automatically updates on the server okay so now I have this emptied here so I right click and create a new file which I will be calling talize C and I will also create a tor lies. H like this and I will Begin by putting a small header so talize Doc and I will include SD iio create a main and this time I will type out the longer signature for this uh main function that is the argument counter and the actual argument pointer like this because I’m not going to be using that in the final version but the client that we’re going to code today uh that will be you it will be used like this so if we run it by doing slash toiz we’re going to enter an IP address like 1 2 3 4 and a port so this uh tool will uh connect to a predefined uh proxy server we’re going to put that in our H file let’s do it right away toal light. and let’s put the include in here instead and in this file we’re going to include our local file so when the file is in your directory you use quotes around it like this and I save this file now if we go into the sociopath window we can see in this status bar down here at the bottom T.C has changed successfully updated to server and if we go into our terminal and go into the directory and check the contents of this file we see that it has uh updated the H is not here yet because I haven’t saved it it uploads on save so let’s do that and with regard to the proxy server I will be using the default values for uh the tour package and that will be using the IP address of one 27 0 0 1 that’s the IP address of Local Host uh and let’s call this proxy and I will also make a constant definition for the proxy port which is 9050 as a default setting save and just to verify now we should have both of these files here right so both the C file and the H file great [Music] so let’s just create the most basic things first I will create a CH pointer for the host name that is the host name that we want to connect to at the end so to speak the server that we want to uh connect [Music] to and we also need to have the port number let’s just do an in for that yes okay so first I want just check that Arc if that is less than three which means that we don’t have two arguments specified on the command line then I want to print to a file descriptor which is called standard error which is uh used for error messages it’s like printing to the screen basically and then we want to do like this usage Post Port like that and as an argument we’re going to give arv Z so arv Z if we on the command line specify do/ talize 1 2 3 four and Port 80 then this is AR v0 this is arv1 and this is arv2 and this is an error so we will return minus one and if we have our arguments we will point the post toward towards arv1 and we’re going to set the port to and we can’t just do it like this because the port is an INT and this is a string so we need to use a function which converts a number in a string form to a regular number a2i let me just check if that requires an include file and we do that by doing Man 3 a2i and we need SD libh which I will put in our header file include STD libh and I will also put in [Music] string.h and uni std. H these are the four that I always put in every C program that I do let’s line up this a little bit better like this okay so how will this work we need to figure out how the proxy protocols socks version 4 uh how does it work so let’s go to Google and if we want to have the technical specification of a network protocol we do like this we search for the uh protocol name socks 4 in this case and we add RFC that stands for request for comments and is a the standard way of describing an official uh Pro so that way you will always get the right one and I’ll take the first one here and increase the font size a little bit this is not a huge file some of these rfcs are very big but this is quite a simple protocol so there’s a two step process first you make a TCP connection towards the proxy server like like any other server like exactly as you did in my web server video and in the uh TCP client video then when we are connected we need to create a network packet which looks like this so from left to right there is a one byte field that is 8 Bits for the VN number and as we can read here that’s a socks protocol version number and it should be four then we have something called CD and CD is the socks command it’s a code for the command and should be one for Connect so there are two different uh types of operations that you can do through so 4 it’s a connect operation and a bind operation so basically a connect operation is when you connect the outwards and a bind is when you uh prepare for an inbound connection towards you uh we are going to do a connect so we will put a one in that field uh then we put the destination port number and we need to format that port number in uh Network bite order which is basically that we switch we we cut off cut up the 16 bytes in two parts and we swap them and same with this destination IP but this is a 4bit 4 by field so 32 bits uh regular in size and that’s where where we put the IP address of the uh remote server that we want to connect to and then we need to put a user ID and I will just put talize there doesn’t matter and then we need to end that uh string with a zero byte as usual and that’s basically it we send send that the packet we get a reply which looks like this and the only interesting field is this CD field if that is 90 then the connection has been established and then you can just send whatever you want if we get another number than 90 then something went wrong and we need to deal with that um and then we will send some data just to see that it works so that is what we need to do okay so I will do like this I will copy this and inside our header file I will create a comment block and paste in this this [Music] one I want the last line as well so I see the number of bytes think I need to change the size here okay this way we see enough but in order to be able to create a structure that corresponds to this design we need to be able to create fields that has the 8 bit size the 16bit size and the 32bit size so let’s start there we will use the typ def command to create our own variable types which will be called int 8 int 16 and so on so if we begin with the in8 that’s basically an on sign Char in see that’s 8bit size so we’ll type type def unsigned Char and then our name for it in 8 then we need the 16 bit size and that is an unsigned short in we call it in 16 and then we need a regular 32bit int so that’s an unsigned int I’m going to call it int 32 okay so now we have the different parts that we need now we’re going to create the actual structure for this packet so we’ll create a struct which I will call proxy request and the first is VM so in8 VM and the next is CD which is also an 8bit then we have the destination Port which is 16 is port and then we have the 32bit destination IP field and then we have the user ID which has a variable uh size but I’m going to create a username of seven characters because that way we can have uh an 8 a 64bit Str variable here which ends in a zerobyte so that’s why seven and not eight so basically I will do unsigned J user ID 8 and this is all we need for the first uh structure let’s create the other one at the same time this one is a little bit smaller so struct [Music] proxy response and we’re not going to be using all these fields so if we look at this one the VN is always zero and the CD will have the code so the CD is the only interesting field here because the remaining fields are ignored so destination port and destination IP are ignored but we still need to have them defined because we need to have the right size of this package so I will do do it like this I will start by creating an 8bit integer for the VN and 8 bit CD then I will just do in 16 and an underscore character and then int 32 and two under score characters we could name these according to this but U I think this show clearly shows that they are not important okay so now we have our two structures we can remove those comments and make this a little bit bigger again and I want to create a type def for these structures so we don’t have to type the whole proxy request every time and I will just call this wreck with a Big R and same here type def stct proxy response and this will be rest with a Big R okay so now I have now we have prepared everything we need basically in this file and we do need a couple of includes though because we are going to use the following functions we will have uh sockets to initialize the sockets we’re going to have connect and we also need close AG tone s and in address so remember what I told you about the network bite order so if we have a port number for example like something like this in U binary so this is a 32 bit no sorry 48 this is a bite so if we do like this let’s say this is a port number and I don’t know exactly what it corresponds to but let’s say for instance that it’s 9050 because it’s a 16 bit field so it looks something like this then we need to copy this right part and put it to the left that is Network bite order that we have the most important bits first and that is what these two functions are for HT s does it for the U the port number and the init address takes a string and creates a big so basically it first take this IP address and translates it to a big number and then it makes this network by order so these are the functions we need uh perhaps I have forgotten any uh other ones but that will be clear when we get to that point so let’s find out what um include files we need let’s begin by socket we do man to socket and why two because this is a system call that’s why how do you know if it’s a system call or a library call try a library call first three if you don’t get a hit or if you get a hit that doesn’t seem right try the uh the two okay so we need sis socket. [Music] I’ll just copy it right [Music] on this and then we need the connect that’s also a system call so Man 3 no man to connect and that’s the same we don’t need it again and what else did we need uh closeth I think that’s un SD that we already have but let’s see so the close that is also a system call and we use it to uh close down uh the connection can also be used to close down a file yeah un SD we had that already and then we need the hton s and IET address so man this is three so h t s this one and finally inet address also a library call so three here we need a couple of include CIS socket we do have already ARA inet we do also have but not netet okay so let’s see if this compiles since we are using a couple of files I think I’m going to create a make file as well so I will create new file and I will name it make file with a big M and then I will just put in [Music] all JCC talc doraliz we’re going to be adding a lot of stuff here later on but for now now this how to do it so let’s uh save and when we have a make file like this then we don’t need to issue the GCC command every time we can just do make and then it will try to compile okay in okay typo so so let’s go into the toor realize. C and this should be an if not an in let’s save and we’ll run make e this time it compiled our tool okay so the next step is connecting to the proxy server because we’re not going to create a TCP connection directly to this host and Port that we specify on the command line we are going to connect towards [Music] the the proxy IP address from the h file and the proxy port 9050 so that we have done before creating ATP client and it’s exactly the same as before so I’m going to make it quite fast if you need to learn how to do that you can watch either my TCP client episode or my creating your own web server series I will explain by haste though okay so we need a couple of um variables first of all we need an INT which is called s for the socket file descriptor return value we also need a structure which is called sock address sock address in and I’ll call this sock that’s where we spe ify all the IP addresses and stuff um okay so let’s start by creating our our socket so s equals socket and this is pretty standardized we always put in sock ey nut and second argument is sock stream for a TCP connection and then a zero for the third argument and if this s is less than [Music] zero then I will use the P error command to easily print an error and we will specify which function that produced that error and then I will just return minus one when we uh create the final version of this I’m going to use more accurate error codes but for now we’ll just do minus one for everything then we will create we will prepare our structure and that’s three things we need to add in order to make atcp connection first of all we need to put the S family to AF IET we need to put in the Sin port and use the H ton s so we get it in network by order and then we will just put in our Port variable here and finally we will put in our sock sin address s address and that will be equal to inut address and our no not our Port it should be our proxy port and it should be a our proxy IP address nothing else okay so these are the three things now we need to initialize the actual connection with the connect command so we do connect and we reference the socket uh the second argument is our structure and we need to create an explicit type casting because we need to change it to Sock address struct a pointer to a sock struct and we also need to send the reference so let’s put an % there and the sock and then we need a size and I will just do size of suck that thought to do it okay so this line will connect to the server but I will also need to do an if statement so we see if it succeeded and this should return a zero if it works if we wouldn’t remember that we can go into the command line and do man to connect and go towards the bottom and here we will find a section for the return values if the connection or binding succeeds zero is returned otherwise minus one so I will just do a simple if statement there’s no need to save this to a variable so if this is not zero something went wrong and then we do p error connect and return minus one otherwise we are connected to the proxy server so I will just Echo that to the screen so we know what’s happening then I will close the connection because I want to see if it works so close s return zero okay let’s see if we did something wrong make it compile on the first run that’s not every time and let’s run it and see what happens right we need to put some something here we’re not going to be using that information at the moment connected to proxy great so it works so now we have successfully created our TCP connection towards the proxy server and the next step is to create the uh proxy request packet according to this structure that we created before we haven’t created any function declarations so let’s do that as well so we have a main function takes in an in and an arv pointer and when I create those signatures sorry chart of course so if we look at our regular main function we use this format right here so H Char array of pointers but when I create the type signature I usually use this format doesn’t really matter okay so that’s the only function that we have this far our other function is going to return a pointer to a request and let’s name this function request and as argument we’re going to take in a sh pointer which is our destination IP and just a regular in for the destination port and let’s make both of these counts as well the count keyword means that we cannot change these variables inside of the function so it’s just input values so this is the signature I’ll copy this and then I will strip it down so it looks like our main one because we don’t need to have the names of the variables when we do a function declaration and why do we do this function declarations do we have to no we don’t we don’t have to but imagine that we put our main function in our C file at the Top If we then and try to reference the request function it’s not going to find it because it has hasn’t been Define yet but if we put our request function on top of the function declarations then it will work so that’s one reason but I think a more important reason is so you can have like a um a better look you can just watch the H file and you see the entire structure in a very good way so always do this if you have a multiple files or a Big C file uh okay that was a small parentheses sorry I copied over this [Music] one there we go and then we go into here and we will create this request so what do we need in order to do that well we need to allocate the memory for this uh request uh structure that we’re going to uh turn and we are going to reference the length of the structure a lot of times so I’m going to create an alias that or a macro and you do that using the Define and then you give it a name I will call this [Music] Rec size and uh what is Rec size it is the size of stct proxy request and let’s create one for the other one as well though Define uh rest size response size and that is size of stct proxy bon in that way we don’t have to manually type out this as soon as we need to reference the the size of the structure and um semicolon at the end oh I misspelled there we go okay so back to the C file again and I’m going to create a request pointer I’ll just call it recre sorry and I’m going to start by uh allocating the memory for this structure so request equals Malo re size like this and now we’re going to fill this structure with the correct data so let’s bring up [Music] the RFC again so the first thing is the VN and the VN should be four so w VM equals 4 and if you’re not familiar with this Arrow that’s basically the same as the dot format but when you’re using a pointer to a structure you use this um Arrow to to indicate that we need to grab into the the reference in order to get the value or set the value in this case okay so VN is four then we have the CD and it should be one because we’re making a connect request so Rec CD = 1 then we have the destination port and we need to put it in the correct format so wck this Port equals and now we use this Hon s function that I talked about before to switch it to network by order and uh is the destination Port then we take the destination IP so w destination IP equals in address destination IP and then we need to have a null terminated string with our variable and I want it to be eight characters so let’s create a definition for that find username toiz cuz we need to remove this e 1 2 3 4 five 6 7 and then a ZTE at the end so so we will use I will use string copy to copy into the W username the usern name and the maximum size is seven and then it will uh add the zabte let’s do it okay so now we have prepared this structure and now we will simply return it like so and now it will be very easy to to hand handle this because we have a function which just creates the entire data that we want to send and we know the size of this structure so we can just use the right system call in order to send it okay so now that we have our function which creates the packet that initializes the proxy connection now we’re going to use it so let’s go into our main function and let’s create a pointer of our structure request type so we can use it when we want to send the data and instead of just closing the connection like we have done here we’re going to set our request variable and use our function and our request function takes two arguments it is the destination IP and destination port and we do already have variables for that it’s the host and and Port variables so we’ll just use some so host and Port like this so now the wreck variable is pointing to a toour packet and we just need to send it using the right system call the first argument is our socket file descriptor which we named s uh the second argument is [Music] the is buffer and I think we only need to do wreck perhaps we need to do yeah we probably need to do a type definition type cast I mean but let’s put put it like this to begin with and watch the warnings and errors if when we compile it that’s usually the best workflow uh and we need the size of the packet and since we know that we we always want to use a 8 by an 8 byte buffer for the username we have a constant size of our uh request packet so we will just use that uh definition that we put in here somewhere it is I think we created a macro yes Rec size that’s the one that is the size in by for how big this packet is so now we send that packet and the next step in the process if we look at our RFC it is accepting this structure back so we can look inside of the CD property and uh look for the 90 code so how do we receive this one well we did use write in order to send the data and will use read to receive the data uh and for that we need a buffer so let’s I think the easiest way will be to just create a variable on the stack for that so buff and then we’ll put the response size as the number of bites and before I use read I always want to make sure that the buffer is empty so I will M set the buffer with zeros and uh use the rest size number of zeros so now we have a clean buffer that we can read data into um yes so let’s do read and the first argument is the socket file descriptor second argument is the buffer and the third is the size like this and if this read operation returns something less than one because the number of bytes should be [Music] returned then we know it the operation has failed and we need to show an error sorry I’m a little bit used to the JavaScript strings there we go and let’s uh free [Music] the the the buffer uh no not the buff free the uh request packet so we don’t have things line around on the Heap and let’s close down the socket file scriptor and return minus one for now so this is if the read operation fails if it has succeeded we should have a packet that looks like this in our buffer but we can’t easily access the values inside of it if we only have a string pointer so we need to create another pointer of the correct type which is our uh structure for the procure response so we will create a rest as well as the wreck and we should just be able to point this towards the buffer and that’s what we’ll do so rest equals buffer I think this should be enough and now we should be able to grab this value the CD value and I like doing it like this I will create a an INT which I will call succeed success and this will be a bullan variable but as you know we use ins as booleans we can use Char and other types as well but usually it’s in and uh this will be used as a predicate I’m not sure if you are familiar with the term but a predicate is basically a a a function or an operation that returns true or false and uh this is American English I think in the British World they use the word property for this but since we already use the property term when we describe other things I think the predicate is a better term anyhow then we can do something like this so we set success equal and we go into this structure and we check for this CD value now we’ll put this in parentheses and we do like this so what does this mean this means that if the CD is equal to 90 then success will be equal to true if it’s not 90 success will be false which means we can do like this to see if it has worked or not and then I want to print out a an error message of my own so I use the fprint F to the standard error way and I want to say something like unable to Traverse the proxy error code and then the error code I need to divide this a little bit I’m not sure you know it but if you have a large string you can always divide it by lesser by smaller strings uh and put them on different lines make sure to encapsulate them in quotes on both instances and then we will show the rest do c the rest to CD value like this and we can also do yeah let’s close the S and let’s free the w return minus one and unless this if Clause happens we have successfully traversed proxy so let’s inform that with a print F at least for now perhaps we will remove these messages when we are done okay so [Music] successfully connected through through the proxy to we will have a percent s colon percent [Music] D and then I will use host and Port like this and now I will close down the connection when we do the when we finish this uh program off we will not be closing down the connection but since we are only checking right now if it works if we are able to connect through the proxy we can close down everything and terminate when we are done so this code will be removed in the final version and we will free the W and return zero like this H the indentation seems to be a little bit off well we’ll see if we get an error okay so let’s compile this and see what happens okay uh and when we are troubleshooting code especially when we have coded quite a lot of lines of code since we last uh compiled always look at the first error because sometimes if you fix the first error all the other errors goes away so don’t get discouraged when you see a full screen of error messages like this just focus on the one at the top uh so what does it say w has no member named username interesting so let’s go into our H file and see what we’ve got user ID okay yes of course so where were was that that’s probably inside our request function right yes here it is so user [Music] ID like this okay and before I run make again I press enter a couple of times so we get a barrier that way it is much easier to see where the last couple of error messages stops and the new batch starts okay so assignment to rest star from incompatible pointer type rest equals buff okay that’s the one I was a little bit unsure about remember and I said let’s uh compile this and see what it says because in some of these cases the C compiler will perform an implicit type cast in this case and uh work it out anyway but not this time so okay so rest is a struct pointer and buff is a string pointer so what if we were to just [Music] do res like this let’s try that first seems like it worked okay so close s data definition has no type or storage class that’s an interesting error message data definition has no type or storage class close s in close in FD uni SD do we have all our include files I have never seen that error message before you SD yes didn’t I call that variable s yes and that’s an INT in in it was only a warning but very weird warning perhaps something else is wrong in its proximity if success F print F and the parentheses then we have the string and then the end parentheses close s what line did it complain about 94 okay it’s not it’s not this one it’s complaining about this one well uh there is okay so let’s [Music] see if success do and then we have this close s close yeah this shouldn’t be here okay let’s do this again okay it compiled let’s see if it works so what shall we connect to I will just do one of my web browsers and you might have noticed that we didn’t put any DNS related stuff in this one so I can’t just put in www Network technology.org or something like that that’s something that you probably can add by yourself see that as an extra task and but for aove of concept it’s not really necessary okay so I will take the IP address of my web server and let’s run talize against that on Port 80 and if this works we should see a message that we have successfully connected to the proxy and we should also see a message that we have successfully connected to the end host through the proxy connected to proxy successfully connected through the proxy to blah blah blah blah blah blah okay very nice so this has accessed the web server through through the tour Network and let’s add uh let’s add some functionality so it can send some data and read some data so we can see that it can communicate with the end host as well that is also stuff that will be removed in the end in the end result so let’s create another buffer let’s call this temp and let’s do [Music] 52 since it’s only temporary I will not think much of it so here we are successfully connected and now I want to send something so since I’m connecting to a web server I can use the head command just to grab the information about the web server versions and stuff like that that’s quite easy to do so I’m going to use the SM print F in order to create the buffer but first I want to use the M set in order to zero the entire buffer so no not I need to remember I call it temp and zero and the number is 512 and then I will do SN print F and we are going to put the result into the string variable the buffer that we call temp and we won’t be writing more than 511 characters and what do we want to put there so let’s do head [Music] HTTP like this and we’ll end by r [Music] n and on the next line I will put in host Network tech.org and and if you wonder what this RN is sorry that is the Windows standard for new l so this R thing is a carriage return which jumps down and goes to the left uh or it goes all the way to the left and the N is as usual the Line Feed Okay so now the buffer is now the buffer contains this [Applause] data and then we will just simply send it so write s temp and I’ll do string length of temp like this and then I want to zero out the buffer again or not the buffer the temp and then we want to read the results so we read from s into temp and no more than 511 bytes and then we’ll just print that to the screen with a regular print s like this let’s put it in single quotes as well so we see if there’s something weird going on that’s a good tip by the way like if there’s a line feed before the the data or something like that then we will see it like this so this will be on one line and this will be on the next sline okay save and now we will compile and let’s run it again and this is the response from the web server as you can see it works we can we are able to communicate through the tour Network and if I connect to my web server we should be able to check the logs and see what IP address the requests came from more log P here we are and let’s do tail D3 access access. look okay so here is our head and if we grab this IP address we see that it’s it’s some kind of German uh address and we can also do if we restart the tour server so we do Etc in tour restart as root [Music] restart like this then we issue the same command again we did get the output like before and if I check the logs once again we get another another IP address this time and if we do a host on that IP address we see that this time it’s in the Netherlands so our program works fine this far but at the moment it’s just a proxy server client it’s not doing what we intended it to do from the beginning you remember I want to be able to do something like talize and then run any [Music] command like curve against some IP address and then I want to in intercept the connection I want to run this command as is but I want to intercept the con the connection that the actual program does and run my code instead so it tunnels through the tour Network any program that we want to run so we can do talize and put anything here we could do like if we have a Firefox installed in the same directory we could start Firefox with toiz and then it will be tunneling through the Tor net work and we could do tell net or SSH that is what I want to do and that is the next step in this process it seems really Advanced but you will see that it’s quite quite a bit easier than one might think so what have we learned today today you have learned how to create a Sox version 4 client and use it in order to connect to the tour Network and next time you’re going to learn how to create this Nifty little tool that I called toy if you like this episode and want to see the continuation or other stuff in this Channel please uh subscribe to this Channel and hit the like button if you think I deserve it and uh thanks for watching thanks for today welcome back everyone to today’s class today we’re going to talk a little bit about something called exor so exor is an operation you like you can do PL plus and you can do minus and then you can do xor but exor uses two streams of bits and it produces different output bits depending on the input so if we have two zeros then the result is zero if you we have a zero and a one then the result is one no matter which it is which but if both are one then there it is zero so why is this useful well this means that if we use this technique in order to encrypt something then we can decrypt it if we Supply the cipher text with the same key as when it was encrypted this is a very basic form of encryption that uh is only for demonstrational purposes it’s quite easy to crack with today’s Technologies and computer power however it’s a good example on how to use exor and in this example I will only make it so that you encrypt one one single character and when you know how to encrypt one single character there shouldn’t be a problem for you to modify the code so it can be able to encrypt any length but only one character in this example all right so let’s begin by creating an exor doc file and we will also have a couple of definitions we will Define the key which also will be one character and we will Define what we want to encrypt so let’s define the key as the character X let’s do big X and and then we will Define the clear text as the letter A so we want to encrypt the letter letter A using the key X and we don’t need a whole lot of includes I will just put the standard input output age Library and in order for us to be able to see what what is happening I will create my own function called print Char which will print the character and the heximal value and it will also print a text string describing what we are printing and this will just be a single print F line something like this so we will take the [Music] character and show its asy character code and uh we could do hexad decimal but I think yeah let’s do hexad deal and it will take three arguments the text describing what we are doing and then the character twice so we’ll print the actual character and its heximal representation and I will put a0 X in front of it to show that it’s hexadecimal and that’s all okay then we go to our main function where we will do the magic so to speak we will click create a couple of Shar one for the clear text one for the key one for the cyer cipher text hard to write write that word and one for the new clear text because we will decrypt it into a new variable okay first we Define the clear text as our clear text definition this one and we will use our print Char to print the clear text before we do anything with it then we will Define the key as our constant key and do the same we will print that on the screen and then we will do the actual encryption so the cipher Cipher text should be equal to clear clear text xor key so this little Char uh carrot character here it’s is is not uh uh what you might think it is uh sometimes we use this carrot character to do when we do like x to the power of five or something like that but in C the carot character is equal to the exor operation okay so now we have created the cipher text variable containing the encrypt text using the key now we want to print the result Cipher text and cyer text and finally we’ll try to decrypt the text into another variable and this time we will take the cipher text and xor the key so as you can see the exact way that it goes forward when we take the clear text uh X or the key producing the cipher text we now take the cipher text xort the key to produce the clear text and then we we will use our print Char function to print our new clear text and that should just about be it so let’s compile this one oh I did something wrong I main that’s not right there we go okay now what line 47 ah I added a parenthesis too much so let’s jump to 47 okay it’s outside of the text but I did see it on the message where is it ah right here that shouldn’t be there all right now it works so let’s run it okay so from the beginning we have the letter A as a clear text and that is 41 in HEX and we have the key X which is 58 when we combine them together with with an exor operation we get a cipher text with a hex representation of 19 and no asky representation and then we exort the text backwards using the cipher text and the key and then get we get a new clear text with the letter a 41 so our code works just fine should be cat not CL car okay so we do two definitions we create a simple function in order to print out the results we set the clear text and print it we set the key we print the key then we do the encryption algorithm so to speak using clear text xor the key and printing that out then we do it backwards we the cipher text exort the key and get the new clear text and press print that out so today you have learned all the race to the exor operation in C thanks for watching and thanks for today what’s up guys in this episode we are going to code our own uh encryption Library it is uh Loosely based on the arc4 cipher but with some improvements which makes it more secure we’re going to expose a couple of uh functions from our library and it’s an initialization function which takes a key as an argument there’s a encrypt function and there’s a decrypt function and finally an un initialization function so it’s very easy to use and U let’s get [Music] started hello everyone and welcome to Today’s Show today we’re going to code our very own encryption Library using the arc for uh algorithm when talking about encryption that is uh one of the more easy encryption ciphers to implement but it’s a little bit bigger pro project than we usually do so I will not be coding inside of the terminal today I will do most of the work through the is code so let’s begin by launching the sociopath SCP client so we will be able to code live against the server I will just go into my I will put it in my temporary directory and I will create a new directory and I will call this Arc for spelled like this so the algorithm is written like this rc4 but it’s pronounced arc4 so I think that’s a good name for the library so I’ll simply create an empty folder and I’ll right click and open an editor then I will have access to the entire folder ins side of vs code like so and I will minimize my sociopath and close down this and I will also log into my server and attach to my screen or uh I will create a new screen instead and I will configure it and as you WR V of and as usual I will write a simple bash script like this just so I don’t accidentally close down this window and terminate the screen so let’s go into my temp directory and go into my arc for and here we are an empty folder so what do we need I will create a two files or three actually first I will have the actual code the ark4 doc like so and as I save we can see here it’s successfully updated to the server and we will also need a Arc for. H for our structures and includes and definitions and macros and such and to make our life a little bit easier I will also create the make file which is going to compile the whole thing and actually I will create a fourth file as well this is just an temporary file we won’t need this file when the project is completed but as we are implementing this encryption it will be easier if we have an example program which we can use to try things out and I will call this example. C because we are creating a shared Library so this Library will be used by different uh c pro projects and that means that the arc for. C file will not have a main function so this example. c will provide our temporary main function so we can run it all right so in the make file I will simply Define the stuff that needs to be compiled so the first thing we will be Ark for. o and you write it like this so the file that you that’s the Target and then a colon and then you write the dependencies so this file will depend on Arc for. C like so and then you Tab and you write the command so I will do GCC d c AR for DOT C like this and I will also turn [Music] on optimizations at the highest level as well as log messages and when that file has compiled successfully we will have an arc for. and then we will create the actual Arc for Library so this depends on Arc for. o and I can’t really remember how [Music] to let’s see all the flags necessary to create the shared Library so I will check how I did it in my toiz make file and I will simply copy this part right here so I will do GCC and we are compiling Arc for. o or linking actually and the output will be called Arc 4.so that’s the extension for a shared library and we want the uh optimizations and the log and then this additional Flags necessary for a well for a share Library [Music] okay there we go so after those two steps our library is compiled but I will also have the example do o dependent on example. C GCC d c except exle let’s see and I will turn on op and well and when we have the object file we can compile example which will need example. [Music] o and then we simply do GCC example. o Dash o example wall two and I will also create a clean which simp removes everything besides the source files so all o files allo files as well as the example binary executable and then I will just tell the make file what we should do as a default when we run the command and I want to compile Arc for and example so this is our make file if I didn’t miss anything I think we should be able to let’s just go into the temp and the AR for and I will set this to my home so the prompt won’t be so big like this and I didn’t save the H file I think and the example and make file there we go Arc for make file Arc for. Ag and example so I should be able to run the make now and we get a reference error for the main but the do all files should have been created yes they did so everything seems to be working even Theo file did be created even though everything is just empty source files and if we do make clean we’re back to where we started okay that’s a little bit of administrative work but it will pay off when we need to recompile and debug our code I’ll close down the make file because we don’t need to do much with that and I will actually start with the example file because if if we create the example first then we have a kind of a road map to the different functions that we need to create later on so I think that’s a rather good way to start I’m going to include the arc for H oops or for H and inside that I will have my regular definitions so I usually start by putting in the STD iio that will be removed later on because we’re not going to use any of these libraries but during development I think it’s easier to have all the usual standard libraries ready to go like so okay so how will this example file work um I’m going to start by just creating function definitions so we do everything in the order that you should even though this is a small file so we’ll have an in main with no arguments and that that’ll be all for now so I’ll create the actual all M and I never seem to learn where to find my curly braces on my Mac all right here they are so I’ll will create I will make this file a little sloppy and easy to work with because this will not be a part of our production code so to speak so I will just do it as easy as it can be for myself so I’m going to create a couple of pointers I will have one for the key and I’ll have one for [Music] the uh Source text that we want to encrypt I will have one for the destination text [Music] and I will have one additional pointer for when we decrypt the encrypted text so let’s call this encrypted instead and this decrypted that’s a little bit more obvious and I think I need to make this a little bit smaller I hope that won’t be a problem for you okay and I will just Define this statically so I will set the key to let’s [Music] see something easy like tomatoes when you run this code for real you should always create a a real encryption key so this can really be anywhere from 8 Bits to 2048 bits according to the standard but this will do as an example and the text I want to encrypt is a part part of a Shakespeare poem shall I compare the to a summmer day okay we will also need to before we do that I need to define a couple of type definitions because I’ll be using eight bits in Gears and I will use 32 bits and possibly 16 so I’m going to define those first so let’s define [Music] um we will do unsigned char that is an 8bit value and I will call this inate and not defined by the way this should be a type definition so a type definition is when you create your own type everything you write is what the source name is and the last one is the destination okay so the next type definition will be a 16 bit int and that is defined in C as an unsigned short int and I will call it int 60 and finally we need an 8bit uh variable as well and I will type this as an unsigned chart in8 [Music] um oh sorry I have done that already the only thing we have left is a regular a 32bit integer and uh that will be well a regular unsign in like this okay so now we have our type definitions and let’s continue with the example main function so we have the string that we want to encrypt we have the key we will also have a um a pointer to a structure which I will call Ark for and I will call this pointer Ark for like this so this will contain the internal state of the encryption engine so to speak and I will Define this as a let’s do it here I will do struct s I usually prefix my structures with an S that’s a stylistic choice though uh so s Arc for and what will this contain well we will we will actually use the Wikipedia page it’s a very good Wikipedia page which tells exactly how to implement this encryption not in a specific language like C but with like pseudo code okay so we have this and now that we have the key by the way we also need to size variables so let’s [Music] do in 16 and what do we need we need two size variables so let’s call those size key and size text and I will just use this string length to define those so SK equals S L key and S text equals s l f okay so now I have all that that I need in order to call the first Arc for function and that is called let me do the T function declaration it will it will be called Arc for in it because it initializes the arc for structure so this will be of type Arc for pointer and it will take two arguments it will take a key let’s do it like this unsign CH no let’s use the orate it it’s not really an integer because this is a string but every every character is an integer so it will be okay I think so in8 key in because if I don’t do it like this if I do sometimes Char and sometimes in eight and then I will probably get this signedness wrong and I don’t want that and we will have an in 16 for the size of the key and I don’t need those in poter in 16 right then we go back here here and we will set our ark4 equal to Ark for in it and we send our key and our s key like so and this is a function that might fail but that’s very unusual so I won’t care for that during this example program but if you write a real production grade program check if this Arc for returns zero because in that case The maloc Returned error otherwise we will get one of these structures back and then we are ready to encrypt let’s add some prints as well so in initializing encryption and I want to have a way of putting this to the screen instantly so I will create a definition which show which call F and I’m not putting this into the arc for. because this is not something I need in the in the actual uh end res in code this is just for convenience so F will be F flash SD out and that basically flashes the standard output buffer so that if I do a print F like this which not which is not ending in a new line it will and if this takes a couple of seconds to initialize then this text will not be printed before this delay which is which kind of defeats the purpose so I will put the F right after like this and then down new line okay and then we will let print out the input first so I will put it in single quotes [Music] and let’s do it like this a new line and then an AR an arrow and this is the front text like so then we do the actual encryption so we will use our encrypted variable so encrypted equals Arc for let’s define this first so this will return a string pointer but I will call it an int8 pointer and it would be called Arc for encrypt and it will take two arguments one which will will be an in8 pointer so the string that we want to encrypt and a size in the form of an 16bit integer like so pretty similar to the initialized function and the arc for uh encryption works like this you you don’t need a specific decryption function because if you try to encrypt the encrypted text it will be decrypted so then it goes backwards so with that in mind we can just create a macro which will be called Arc for decrypt with two arguments X and Y and this will just call Arc for encrypt with X and Y so it’s not really necessary but [Music] it makes it a little easier to use and in order to make this encryption function work we need another function called Arc for bite which produces one single character of encrypted text so this will be an INT 8 and not a pointer just a value now that we have our data types and our function declarations done we can continue with the example. C file so the encrypted variable will be equal to Arc for encrypt and we will send in the uh from text and we will also send in the size of the text like so and this is a function which shouldn’t be able to fail which means that the encrypted variable will now contain the cipher text the next thing we need to do is create a function which can will make it possible to Output the encrypted text in some format because the um the encrypted text will not be printable characters it will be any number of different integer values and I’m thinking about putting using an output like this so one B will be represented by two heximal characters like this like this so this is one b and then two byes per group and each group will be separated by a space okay so this this function uh will uh will not be a part of the library itself only this example file so it shouldn’t return anything and let’s call it print bin because it’s binary data and it will take in an INT 8 array pointer let’s call this text it’s not really text but whatever and then we will have an in 16 for the size like this and all we need to do is iterate through the text and print those bites two at a time so how do we do that in the easiest possible way there are several approaches but I’ll I think I will just I will just create an in32 as an iterator and I will have an in 8 pointer as well and I need to assert that size is bigger than zero and what is assert assert is a function which checks if this predicate function is is true and if this is not through the whole program halts so it’s quite good to use in situations like this both in this example file because it’s easy and it doesn’t matter really if the program exits and we can also use it in our production code in some places because we are coding a library and the programmer should s the ra right arguments if not the program should hold I think all right so we need to go into this Arc for and include what’s its name it’s assert Ag and in order to get all the functionality we also need to include our number. H like this now we jump down a little bit same here okay so we know that we have an input which is let’s call it input instead that we have an input which is a well which contains something length is bigger than zero okay so let’s do a loop then so four and we will [Music] do let’s make this an in 16 instead that will work better together with this 16bit size so let’s and I want to make this const as well here okay so let’s set I to size and P2 input we’re going to continue the loop as long as I is positive so I’ll just put I here because it will decrease every iteration and it will after a while go to zero and the loop ends and the PO pointer will instead increase every iteration okay so if let’s see I need to check something out so the first iteration then let’s say we have a string which is 32 bytes so I will be I will be equal to 32 and we will output to one B of data then it will be equal to 31 and we will output two more so let’s see I think we could write it like this so if I + one let’s see if I + 1 modulus 2 if that’s the statement is negative so it’s equal to zero in that case I want to print f space and in any case I will print out a head ex a decimal value with two two digits and this is what we want to print out I think this will be correct um so this basically means that if we are even so if I I + 1 is even then we will put the space and we will also use our macro F so it will uh uh print this no we don’t need that by the way because we will end this with a new line anyway so that will flush the buffer this should be all I think and let I have forgotten something but let’s try it out so what can we try it out on we don’t have all these functions [Music] yet so let’s comment this out and this as well and this is okay and what shall we print as an example we can print the key so print bin that’s actually not binary data but it will work the same so we will print the key and S key is the size turn something like that let’s see if this compiles or if we need to remove something else make a lot of warnings type Def unsigned sure expected before unsigned before unsigned uh I have an empty struct that’s probably it let’s just put something temporary here then [Music] maybe it is because of the position sometimes you you need to do one thing before the other Etc uh forgot to end the struct with the semicolon is it still complaining type ofure in if we add our type def [Music] for for struct does that error as well type of struct is ar ar for uh it’s not uploading okay I got disconnected one good thing with the sociopath is that if you reconnect like this you don’t have to do anything else it remembers and continues to serve all of your files so that’s good okay let’s save this again and this one and let’s jump down a bit clear the screen and let’s make it again okay finally pointer Targets in passing argument one of print pin differ in signedness uh uh okay so this is what happens if if I don’t use my in a eight everywhere so where did I not uh here let’s just change this to int 8 and everything should be okay okay we’re down to one screen of errors and warnings [Music] almost does it still uh seems like it needs a type cast because the strings are generally not like these static strings in side of the code they are generally not un so let’s do a typ cast in a poter and same here in poter key ah so SD L needs it as well I could just make these strings signed but then I would have the same problem in the other end instead because the encryption uh standard requires them to be unsigned so let’s just type cast this as well in 8 like so do we use them anywhere else except our own [Music] functions print F shouldn’t care right let’s do it just for the sake of like [Music] this okay let’s try it again at least we have very clear and precise error messages in see did I go to far make clean make S key equals didn’t I save [Music] save why does it okay it’s higher up in the code right in eight star and there we have it okay that should be all right make clean jump down make what does it say this time point or Targets in passing orent one of string length di in different ah I did it in the wrong direction okay that’s kind of funny so instead of in 18er let’s see there there there and there we should just have Char because we have them as int8 but the functions we’re calling requires them to be regular strings so a sign CH pointer okay this time it should look a little bit better I think make clean jump down a bit and make warning pointer Target in assignment from sh to 8 AKA unsigned different sign do so it doesn’t seem to be enough by doing this it this way okay let’s do it the other way then I will undo until I see this change like so so now all of these key and this this will probably not be but here we can do a conversion in the other direction instead and that should be all make clean jump down make okay now we’re talking warning unused variable that’s an annoying message if I don’t want to use my variables I don’t use my variables but okay so let’s do something like key equals from equals encrypted equals decrypted equal key = Z is that enough maybe I should end it with a semicolon operational key may be undefined variable s text set but not used right so it wasn’t enough to mention the key twice this is only set and all of these are used so we need a key [Music] what [Music] about from equals key okay now what s text but that’s an INT right yeah I haven’t used that yet because we haven’t gotten that far these are only warnings by the way but I when I try out my code and I want to remove everything of the sort uh so which is this this is [Music] the text so we will change the key later on let’s just [Music] do s key equals s text equals zero now it should be completely Warning free I believe no one more warning unused variable Arc for okay I haven’t used that I can just let’s comment that out for now make clean make okay finally let’s see if this works as intended example okay so shall I compare the to sumers day and then I am showing some of the key but I am showing half a group here and half a group here what will happen if where is it if I just do I here okay now it looks good it prints out in heximal characters in nice formatted group very nice that means we can begin with the actual encryption code now finally so let’s go over to the arc for uh H and begin working on our structure this will contain the internal state of the uh of the encryption engine so to speak so let’s go to that wonderful Wikipedia article so Arc for wikii and I want the English speaking Wikipedia let’s hide this and make it a little bit bigger for you guys and let’s do something like this let’s use the whole screen I will probably be looking at this anyway so there’s a lot of text here and some of it are warnings that this uh encryption standard isn’t secure but I have read through all of that and I’m not sure if I agree actually well this the thing is they claim that the out put of the encryption is distinguishable to when compared to purely random byes of data and that could be potentially be used to backtrack and crack the encryption and it has indeed been used for example the wifi encryption standard web used exactly this encryption with very small keys and a spe special kind of U seeding algorithm which they were be they were able to crack it in the wild in a couple of seconds but that’s only in combination with a web technology and there has been some talk that in combination with the TLs the encryption standard on the web it’s also not safe and it’s not safe the first couple of bytes which it produces is not safe so since we are using this encryption firsthand in our own code not together with anything else and I will also create a mechanism which will disregard the first like 500 million output bites which will stop all the other cracking techniques so I think with a big enough key which is um randomized in a secure manner I think ark4 is still secure Okay so I don’t you don’t need to read through the whole shebang but those gray information boxes are very good so there there’s two steps Step One is what I call the initialization of the crypto that’s when you only take the key and you prepare the internal state of the encryption engine and this is what you do and then the next stage which happens every time you need to encrypt one bite or more exactly produce one bite of the keystream data so then you do this so let’s start writing now let’s begin by creating our Arc for struct I will zoom in here a little bit not that much temporarily so we can have both on the same page um so if we look through this what do we [Music] need we need an 32bit or we need an 8bit INT which will go go from 0 to 255 we will need a an array called s which will be consisted of 8 bit values and 256 of them then we have the J value same as I one in8 and then we have the [Music] key and that’s basically it so let’s summarize we [Music] need int uh I in 8 I J and later on we will need a k so I’ll put it here and then we will need the array so in 8 s and 256 of them so we have I with J we have the K and we have the S do we need anything more down here we need temporary variables as well but then I won’t put them in the struct so okay this is this is all we need for our own structure so let’s begin writing on our let’s begin writing on our initialization function and this will let’s copy this whole thing let’s include our let’s include our Arc 4. h there’s something weird going on with the Caps look include r4h I wonder if you can disable the caps lock I never use it anyway I use shift okay let’s see include AR for. H and then we will do the visualization function so it will return an arc for structure pointer and the first argument is the key the second is the size of the key like so and the first thing we need to do is allocate space for the uh for the actual structure so I will create um point a point pointer for that I’ll just call it P because we’re going to reference it quite a lot and P should be equal to Malo and it should be the size of stct s AR for so the size our stct that many bytes of memory we shall we shall allocate and here I will do an if clause [Music] so let me just check the return values for my Look Man 2 No Man 3 Meo so I know it Returns the memory address but if it fails [Music] return [Music] value they return null and they set arome okay so let’s just do something like a ser insert P [Applause] error I remember then it will check if this has errored out and if so display an error message and quit because if you can’t allocate memory for our structure there’s no point in continuing show okay so now that we have allocated our structure now I will just do this and I will work in the following manner let’s close this down and change up the size a little bit and then I will paste this in and make block comments out of it I think it’s command this or control this let’s do something like this instead oh annoying I never seem to learn vs code for Mac I know all of these different things on my PC but it’s not the same on my Mac well well this works too okay so now I have in the comments what needs to be done and then I will just do it but before we begin I want to zero out all the state variables so let’s do something like no let’s just do a simple simple thing in eight X and 4 x = z x less than 256 x++ and we want to take the PS so that is the this array I want to zero that out so PS of x equals zero and then I’ll just do p i equals P J equals p k equal zero I like starting from zero instead of random randomness okay so the first thing is this Loop right here we will iterate through 0 to 255 with this I variable and we will set s of I to I pretty simple stuff the code will look kind of difficult though but it really isn’t why is this not oh never mind okay so for p i = z and p i less than 256 p i++ and p s of I equals I okay this is done so if we do one thing at a time it’s quite simple to do this actually can’t say that for every crypto and then we will set J to zero but we have done that already so we will jump into this Loop and we will let the the I variable do another uh ENT identical for Loop so let’s just copy this line like this and what will happen then we need to Temporary variables as well by the way so we need int 8 I will call them temp one and temp two and I want to zero them as well from the beginning so let’s just do temp one equals tempure = z like so okay so what will happen inside of this Loop let’s remove the things we have done already okay so this is a rather difficult line I want to break them down so what’s the first thing that happens right here well the parenthesis is evaluated first so let’s set let me see key I mod key actually let’s evaluate this first I mode key length so temp one will be equal to key so it will be key of I key of I no where am I we are here right so I mode key length so p Arrow I modulus key length so that’s the size okay so this part is okay now we can take the rest of this parentheses one at a time so P J [Music] no temp 2 = PJ plus p s of I plus key of and then the stuff we evaluated right here so key temp one and then we will set P J so now we are doing this part so PJ should be equal to everything in this parentheses which was temp two and mod 256 modulus 256 like this and finally we should swap the values of s of I and S of J so let’s set temp one to p s of I no not just I we need to change those occurrences to [Music] Pi and p i there’s a lot that can go wrong here as you can see you need to be very precise so Temp and that is why I I could do everything in one line if I wanted to but it’s very error prone and that’s why I break it down with these temporary variables so temp one is equal to p ps pi and temp 2 is equal to PS PJ and then we will just swap them so [Music] p s of p i equals and here we see that temp 2 equals this no temp one equals this that I’m working with now which means it should be equal to Temp 2 instead and then we have PS of [Music] PJ which is currently equal to which is currently equal to Temp 2 and it should be equal to Temp one and that’s it the code is very difficult to read but it’s quite simple and it’s quite easy to follow it step by step if you break it down into smaller steps and that is basically it I’m going to do one more thing though because if we go back to the Wikipedia page and we go to the next step we see that they zero out IJ and then they have an endless loop which happens every time you encrypt a character so we have a function which encrypts a character which means we only have to worry about this but this part we should put here in the initialization function because then we can just do several consecutive calls to our Arc for bite function so P of I equals P of J equals zero like so and then we just return P I think we did it right if we go back here and we remove this line and put this line back then we can print instead of printing the key let’s print [Music] let’s print Arc for S so the initial state of [Music] the the initial state of the encryption engine and I will put a one of these on top as well so we may see the difference no sorry can’t do that we haven’t initialized it yet but okay let’s see what happens clear jump down a bit make clean and make okay couple of Errors if we go to the very beginning warning suggest parentheses around assignment used as truth value well I want to use it as a truth value I I don’t really care for warnings like this I I if I want to code it this way I will code it that way implicit Declaration of function assert P error okay and here I forgot got something and Arc for has no member named s okay so a couple of more small typos uh if we begin in the H file I guess this is the problem is this a big S or small s it is a small s so why doesn’t it remember called s did I perhaps Arc for p that’s weird maybe it’s something because of this we should check if x is less than 256 so that was an easy one and what else assert peror where is that Lo okay at the Man 3 assert [Music] P okay I need this G Source [Music] thingy let’s try it again rank clear jump down a bit clear and make boom okay in 8 i j k unknown type name unknown type name in8 uh I put this before these let’s move them so I don’t like you have to break this up but what can you do this this just a warning error I UND declared okay I missed one line [Music] 18 WR 8 so this should be p i and this should also be p i okay what no error Arc for Undeclared now the problem must be higher than that Arc for Undeclared in example and pointer Targets in passing Arc for init key sh star that’s weird didn’t I use my in 8 for that function declaration let’s check it out so in8 [Music] key and in8 S let’s put this back right away [Music] and okay it’s this function in 8 [Music] inut 16 well where is it let’s check it out again so expected [Music] in8 Arc for a nit key pointer Targets in passing argument one of AR for in it differ in sness because this is a char inate [Music] key so key is a [Music] Char okay let’s type cast it [Music] down where do we have it’s right here okay so it’s currently a let’s see it should be an in 8 so okay let’s see what we have still a warning about this one but that’s nothing we can do anything about un reference to Arc for init uh we need to link that [Music] one let’s just no so go into the make file and then we will do let’s make it easy I will just do uh Arc for.so as one of the input arguments so clear jump down a bit make and now it still doesn’t compile undefined reference to Arc for init what did it draw GCC AR 4.so [Music] do do I include it in the header file include Arc for. H include Arc for. H Arc for init and if find reference okay for the time being let’s cheat a little bit I will fix this later around I don’t have the patience right now so I’m going to go [Music] and when we compile final program we do AR for. instead like so okay this time it worked we probably need to explicitly export uh the functions when we use the the share Library I will dig into that in a little bit but now we do have ourselves a binary so let’s try it out that doesn’t look very good let’s do M TR DF M look I don’t know look let’s try the S right initializing encryption H how did I write that if Clause by the way maybe I reverse the conditions let’s see if be my look okay this should [Music] be the other way around so if P all right make clean clear and we run example did it remove everything when I did make clean Arc for CH HC yes so how come it freezes there Malo size of struct s AR four if that is zero assert P error for X = 0 x less than oh 256 I think that zero means that it’s some weird number format okay no errors at all no warnings even but the same outcome what is this do we have an endless loop on our hands that’s probably the only possible thing right so p i = z while Pi I is less than 256 maybe we should do this with a little bit bigger structure um this could be in6 since then we are probably overflowing that 8bit variable so that was is n the case 4 x = z and what is X x is also an in8 so that should be the same problem though right there we go finally okay so this is part of the internal state of the of the encryption okay so the next thing we need to do that is creating the arc for bite function which will create one single bite of the key stream and the key stream is what we will use to encrypt and to decrypt stuff so let’s begin I will have in 16s with temp one and temp two just like before and we do need an argument by the way we need to attach the the structure so let’s alter this and put in the arc for Star so we can have access to the internal state of the encryption and just like before I will go to the Wikipedia page and this time I will copy this part so in this code studo code right here they use a wi Loop and they loop as long as it’s generating output but will not do it like that instead this function will be called each time we will produce one bite so we don’t need this Loop that will be handled in the encryption function so let’s do it like before and take one line at a time so we will do p i [Music] equals and then p i + + one and we mode it with 256 first one is done then we do similar with the J part so PJ equals PJ plus PS of p i so we just replace the variables with our variables inside of the structure and we mode this with two five6 just like before okay then we will swap the values so this is like we did previously with the um the initialization function so I will let temp one equal p s of p i and temp 2 will equal PS of P J like so and then I will just I missed the S right here and then I will just do PS of p i equals something and PS of P J of p i PS of PJ equals something okay so temp 2 equals the J part which means it should equal the I part now this equals temp 2 and the PJ should equal temp like this and then this one is done as well why did it mess up the indentation never mind okay and then we have this T variable that is their version of our temporary variables so we’ll just continue as before so temp one equals in the parentheses p s of p i so this is not really a spectator SP Sport I hope you don’t find this too boring but we’re almost done plus [Music] p s of [Music] P J and then we mode it with two 5 six and then we use the K variable for the first time so p. k equals p s of ter one and this is the first final output bite as we can see right here so let’s take care of these indentations and then at the end we just return PK like this and then we have our Arc for by function which is the most important in this entire project so so the next step will be to implement the arc for encrypt and this is quite straightforward to do now that we have a um Arc for bite function so let’s see we need one more argument we need to include the Arc for structure so AR or do we yes we do Arc for star and we go here and do Arc for p and in 8 this will be the what shall we call it the thing we need to encrypt the clear text let’s call it CT for Clear text and in 16 this is the size size of the clear text that we want to create and we’ll return this as a um well as a Char buffer a regular string actually so let’s create a in6 which will hold the amount of memory we need to allocate so let’s call this mem size and we will need exactly as much memory as this size + one okay so we don’t really need to because when you encrypt something if we encrypt ABC the resulting Cipher text will be something like this it will be the same number of characters which makes it quite convenient for us we don’t need this variable instead we’ll just do um let’s create a variable first so let’s call this cyer text and let’s call this clear text because both will abbreviate to CT and we can’t mix those so in8 Cipher text and Cipher text will be equal to8 look and we [Music] want size + one size should be enough really but I like allocating one more just in case we will also need something we can use as a counter let’s call this in 16 x we do a for Loop where we set X = to [Music] Zero and we’re going to loop as long as X is less than the size and x++ and what are we going to do at each iteration let’s create a let me see we need this and that okay let’s do it like this so the cipher text of X will be equal to the clear text of X and then we take this symbol and some people usually mix this up with the power of but this little symbol in c means exor so exor is a binary function like do you have if you have two zeros the result will be zero if you have one one Z and one one and a one the result will be one if you have a z and a one so the other way around it will also be one and finally if you have two zeros it will be zero so that is what xor is it’s usually used in conjunction with uh the key stream that a stream Cipher like Ark for produces so here we will just call Arc for bite with our p and that will return one BTE of key stream which we will exert with a clear textt and that will produce the cipher text and let’s do a an error check here as well so if Cipher text is zero then we want to um [Music] assert P error R number like so and if everything goes well we will simply return our new buffer Cipher text quite simple straightforward encryption function and we need a decryption as well but that we have already defined because it’s the same function just that we give it the the cipher text instead of the clear text and the key is the same so basically this part is the same okay so that is done as well and before I forget let’s see encrypted equals R [Music] for so we can take this back now and we encrypt the de clear text and we print out the the encrypted Sor this should be the size of the text this should be the encrypted because this time we don’t want to check the S variable in the structure we want to see the actual encrypted text yes okay so after we have printed the text what do we do do we just use the decryption function no we can’t do that because in order for everything to be the same we must uninitialize the uh the arc for and we need to reinitialize it with the key again so we start everything from scratch and then we can start to decrypt otherwise it won’t work so let’s create [Music] our uninit function as well and that can be avoid Arc for let’s make it easy for us for the time being because there’s only one thing we need to do at the moment when we when we uninitialize and that is to free the um memory allocation so let’s Define arc for un liit of X as fre X I will also need to find let me just do a fast Googling after export C shared Library function because there’s a special string we need to use to export the functions let’s [Music] see this one so let’s make a definition we Define a keyword named export and it will be the same as this so all the functions that we want to export like the arc forb function we don’t need to export that because the end user will only use the encrypt and decrypt functions and the init so we put export before this and before this say and we need to do the same here so export and not this one but this one export like so okay so that that is done as well now we may continue our example so we have printed the the encrypted strings now we’re going to uninitialize so we do Arc for un init on the ark for pointer then we repeat some of the steps like before so let’s copy this part there we go [Music] go and let’s create another one of these CED so I will copy this part for okay something like this and let’s put the arrow one two one two like this instead okay so we initialize [Music] and we need to change the order of these because we need to decrypt this first so it’s initialized now we will create our decrypted so decrypted equals and we will use the decrypt function but but as you know it’s the same the only thing we’re going to change is the from here we have the cleare text before now we will do the cipher text which we get from this encrypted call so where were we decrypted equals and this should be encrypted and everything else is the same and this should be decrypted as [Music] well and then we don’t need to print the binary okay so if we have done everything correct then [Music] the encrypted the decrypted text should be the exactly the same as what we had from the beginning so we take the text we encrypt it and we decrypt it back to the start so let’s see okay let’s save and we make clean jump down we clear and we do make okay not a lot of errors and warnings let’s start from the beginning error T undefined size plus T text 54 in Arc for. [Music] C 54 Cypher text size + t + 1 should be plus one okay we got more errors let’s do make clean first make okay warning this four clause does not guard 4 x = z while X is less than size x ++ x = z x is less than size X ++ which shouldn’t be a problem this St doesn’t guard this statement return CER but the ladder is misleadingly indented okay so it even checks my indentation thing but sometimes that’s good actually I have corrected errors in the past because of that so let’s see what it [Music] says okay it’s this part let’s move it here we make clean we go down and we clear and we make again okay passing argument one of Crypt from incompatible pointer type Arc for encrypt from okay let’s see Arc for encrypt from encrypted equals Arc for encrypt from and from is set to this okay we probably need to type cast this down but it worked before right never mind in int 8 star let’s do it like that do we have any more occurrences so the same decrypted no okay let’s try again make clean and make all for encrypt from incompatible pointer type encrypted equals uh wait a second I forgot to attach the structure right we did change the signature of that function so where were we look cryp the first argument should be the arc for like this and same with the decrypt so Arc 4 and we need to add a variable to the macro as well so XY [Music] Z XY Z like so let’s try again make clean clear and we make and we have this sness problem again so encrypted equals AR for encrypt AR for encryp so let’s see encrypted how did we declare encrypted okay let’s move this to its own instead decrypted decrypted as well I think so in eight encrypted decrypted we make clean and we clear and we make okay almost there another okay that’s our temporary assignment we don’t even need that anymore so let’s just remove this part and this as well save make clean clear and we make okay it compiled let’s see what happens okay initializing encryption done and then then it shows the string that we want to encrypt and it shows the hexad desmal version of the encrypted text then we reinitialize we feed it with the cipher text and we end up with the same string as we had from the beginning so everything works the only thing we should add to this that is the remember when I talked about the that some people think that the arc for encryption is not safe one of the biggest concerns was that the first like thousands of or millions of uh bites is um not good enough so to speak so we need when we initialize we need to like I call it to White Wash we need to whitewash away the first like 50 or 500 million [Music] um of these yeah so let’s go into our encryption function no our initialization function this one and I want to create an M32 which I’m going to use as a well I’m going to use it for a for Loop basically I don’t really want to call it I because that makes it interchangeable with this Pi so let’s just call this C for count n for number and is good and let’s go into the let’s see Arc for and we create a macro for this so we Define arc for white wash and we need a we don’t need an argument actually and what we’re going to do if by the way we do need an argument let’s take the variable for the loop as an argument so the only thing this will do is a for Loop where we go from X = Z while X is less than um let’s call it white wash Cod or what was let’s call it m so this these are millions of iterations so X is less than Ms * 1 1 2 3 1 2 3 and i++ and the only thing we need to do is okay we need one argument more the only thing we’re going to do let’s do it on the next slide uh we will call Arc for B f with the structure or pointer of the structure as an argument so basically that we will call this which it will generate a a bite and each time it Loops it will do that but we’re not going to do anything with that bite because all we need to do is get it had in the well in the state so to speak but if we do it like this then GCC will recognize that it’s redundant and it will as part of the optimization it will just remove this so we will need to typ cast this to something called volatile in8 like so and that basically means in this context that GCC should not uh optimize it okay so let’s put this as part of our initialization so when we are done with the rest of the initialization steps at the end here we will simply call The Ark for white wash and specify our variable for the iterations and the name of our structure which is p like this okay and if this works we should see that it takes uh longer when we run this initialization a couple of seconds uh we also need to define the M’s so how many million iterations should we have and I want five 100 million think that ought to do it if you think it takes too long when you run this try changing this to 250 or 100 because I have a quite fast CPU so this should go quite fast and we save everything and hopefully we haven’t introduced any additional errors make clean and we clear and we make yes we did okay what does it say okay i++ that’s [Music] wrong where were we here so it should say x++ right all right let’s try it again clean down bit and we clear and we make it compile let’s run it initializing and as you can see it takes a couple of steps and then it does the same as it did before only this time it’s probably safe as long as we have a really good uh encryption key which we don’t at the moment at the moment we only have in this example at least we only have the the word Tomatoes we should randomize a 20 48 bits key if we were to use this in the wild but everything works exactly as we intended it to so we have successfully implemented the arc for uh crypto and we have turned it into our own our very own uh Library which can be shared between different applications and when I create um a project for transferring and encrypting files I will use this library for that so then I will show you how to how to use this like library in your code but I hope you enjoyed this and don’t forget to subscribe if you like this and want to see more there is a lot of uh Advanced to see videos coming forward so don’t miss out and stay tuned thanks for watching and thanks for today [Music] the first thing I would want to do before we start with actual encryption tool is we need to install the uh the library so how do we install our own Library well let’s go into our uh directory and let’s alter our make file a little bit so if you remember the ultimate Target of this make file is to create this Arc for.so however I’m going to rename it to lib Arc for so because it will be easier to uh use it if it has the correct naming standard I will also have to check what the correct Library directory is before it was always user lib but now at least on my 64bit Linux system it is this one so you need to add this x86 Etc so let’s grab this and um we also need the include directory but that’s just user include as usual I think us include yeah so let’s create two variables one which is going to be the ink deer and I will put user include that’s where we put the H files and then lib D that’s where we put the library file so when we have compiled lib Arc for.so then we will copy lib Arc for.so to the let’s see the uh lib deer and we’re going to copy The Arc for. to our ink there like so and then we’re going to run the command LD config which will update all the configuration files necessary for the library to work okay let’s try it and we need to run this as rout because we don’t have right permission to that directory so let’s begin by doing make clean and okay by the way it will be better if we create a new Target which we’ll call install and let’s grab these three lines and put them here instead so in this Arc for we compile the actual library and then we do make install as its own command to install it uh so make clean let me just clear so make clean and then make and finally Soo make install okay no errors so let’s go to the directory for today’s program I’m going to call it um f see and I’m not going to tell what the fs stands for but the E stands for encrypt and that’s because I don’t want to spoil what the ultimate end with this project is and I’m going to tell that in a later episode so let’s create a test file test. C and we will include just the standard iio and we’re going to [Music] include we going to include our own arc for. H and we use these angle brackets because now it is installed globally on the system and then I’m going to just create an empty main which return zero so basically I just want to see if it compiles um okay we need to let let’s run one of the functions in that Library so what do we have we have AR let me just let check so more youer include AR four [Music] so let’s do Arc for init it takes [Music] the the key and the size of the key that’s right so Arc no Arc for init and a key and the size of the key invitees so five this should work and let’s cast this to a volatile so let’s cast this to volatile uh Arc for pointer and that’s basically just so the compiler won’t simply ignore this line because we don’t do anything with return value okay so then then we first compile it with the dash C so test. C and we get the object file and now when we’re going to link we do GCC test. o o text and we uh if we don’t add anything else we get the error that it doesn’t find Arc for in it but this is globally installed on the system so all we need to do is add- L Arc 4 and it compiles and run great so so now we have installed our uh Library okay guys uh let’s end there for today and we will continue this uh project uh another day don’t forget to like And subscribe and thanks for watching and thanks for today sup guys welcome to Today’s Show today we are going to answer this question y 755 you have probably sometime used the command change modk 755 and the name of a file or directory but what does this 755 mean in the detail this and more we’re going to talk about today when we are discussing Linux file system [Music] security and this topic will be divided into the following different things we are going to talk about file permissions uh and that also is applicative to uh directories uh and it’s a huge part of the Linux and Unix security we will also discuss the different targets that you can set these permissions for and uh we will also discuss the change mode command in detail how to use it and if we have time left I will also mention the change own uh command plus I will be teaching how to view permissions as well so let’s start with the different permissions that are available on a Unix and Linux system so first and foremost we have read and read is what it sounds like if you have the read permission on the file you can open the file and read its file contents if you have read permission on a directory you may list the contents of that directory all the file names so read has the character flag of R and that is important when it comes to the configuring of permissions using the change mod command and also while viewing the permissions but there is also a numeric representation of that uh R flag so for the read permission that is number four and there is also a binary representation but I’ll get back to that in a little while then we have the right permissions and that is a w as a flag and number two in the numeric representation so what is the right permission well if you have the right permissions on a file you may edit the file alter the file contents and save the file you may also delete the file and uh if you have the right permission on a directory you can do basically anything almost you may uh delete files you may create files rename files but there is also a third very important permission which is called AIS and that has an X in the flag representation and a number one in the numeric representation so what does access mean read and write permissions are quite similar for directories and for files but access differs quite a lot so if you have the access permission for a directory you may enter that directory you may access the directory so basically it means you can CD into the directory uh if you only have the access and not the read you may not do LS and show the contents of that directory but you may access it and you may go to sub folders if you know the name of them and if you have the access permission on a file on the other hand that means that you may execute that file so executing a file that’s basically when you run a script or when you start a program so for example the LS command is a program if you have the X flag you can you may run the ls command otherwise you will get a error message saying permission denied so that is basically it when it comes to permissions but I also want to talk a little bit about their binary representation so let me just scroll a little bit okay so why are we talking about binary that is because I want you to understand how this system is constructed it’s a very very intelligent system which are based on those flags so this kind of flag system is not only used for permissions it’s used for a lot of different things in the Linux operating system but also in a lot of lowlevel code like C programming and stuff and you will soon understand why okay so if we convert the number uh one to Binary with four digits we will get 0 0 0 1 okay if we convert the two we will get 0 0 1 0 and notice that we don’t have a three we have a one we have a two and we have a four why is that well if we convert the four to Binary then we get 0 1 0 0 so a pattern emerges what we can do is we dra draw a line right here and right here and then we see that all those ones are in different columns uh which means that we can combine them as we would like so let’s say we we want to combine the read and the write permission that would be the number four plus the number two = 6 so if we give the number six when we configure uh the permissions it will set both these two flags and if uh you use the ls command to check the permissions then it only needs this six because if you look at these three numbers 1 2 and four the only way to produce a six is by using the four and the two and that is true for all possible combinations of these values as we can see here the ones are in their own column so if we set this or if we set this or this it won’t alter these ones and what is it that mean well it means that with one single integer we can basically store as many flags as we would like at least up to 4.3 billion or whatever and we can store all possible combinations of these flags as well in one single integer and that is a very very powerful way of storing data okay the next thing we’re going to talk about is the targets and the output of the ls command and let’s start by talking a little bit about the targets because we have these permissions read write access but who do we give the permissions what do we set it on well we have for every file and every directory we have three different Alternatives we have the owner and that is also called the user we have something that is called group and we have other and these are kind of self-explanatory the user or the owner that is the owner of the file basically so if you have created a file in your home directory for example then you are the user or the owner and uh that means that you’re allowed to change the permissions if remove all the permissions then you cannot open the file but you may give yourself read write access and then open the file can also delete the file and stuff like that so for you you need to decide for every file in every directory if the owner should have read or write or access or any combination of the three and same goes along for this group so every user on a Linux system is a member of at least one group but possibly several so basically the administrator the root on the system May create the those uh groups and you can be a part of one group or you can be a part of uh thousands and you can be part of named groups or simply a numeric representation if you set permissions for a specific group then you have endless possibilities because if you just have these three different levels the owner the group and other other is just applicative to those who are not the owner and not the member of any group so it’s a very simple uh system with small building blocks but you can create really powerful things with it and we are going to talk a little bit about the flags of these targets as well so let me just put them down here again so the user is the official name for this owner of the file so I will call it user from now on but sometimes it it’s being called the owner as well and then then we have group and we have other so it’s very easy to remember those flags because the user has a u the group has a g and the other has an o so when you set the permissions you have the possibility of using these Flags to specify the target but there is also a combination of all these which is the a flag and that basically stands for all so it Alters all these three targets and sets the permiss permissions you specify okay what else well you may also use combinations of these so if you want to set for the user and the group you just do U or other group OG so AC a system but kind of simple to use anyway uh another thing I’m going to do is I’m going to color these different uh targets so the user will be yellow in this example the group will be green and the other will be purple or possibly pink and and then I’m going to zoom out a little bit so we may see everything here okay so if you do the regular LS command then you will uh only see the names of the file by default unless you have changed the default settings by an alias or similar but if you do like it’s shown here ls- A L and this is an L A small L not one so ls- a then you get one line per file or direct directory and you get some additional information like the day it was altered and the the the size of the file uh and stuff like that and then we have the names to the right but the thing that is interesting in this example are these right here so perhaps you have seen this before but haven’t given it much thought these are the different permissions and it might if you look if if you’re not familiar with this it might be difficult to make sense of this because it’s just a lot of different characters and you may not see any pattern here but let me do this if I take my Jello pencil and I highlight this part and I’ll take my green and I’ll highlight this and finally I will take my purple or pink and highlight this and then I will zoom out a little bit again do you see now so in this example if we look at the first uh the first uh file or directory the ETC then in yellow we see the users permissions that’s always displayed first so the user has read right access and uh the next one is the group and as you can see there is read and there is access but there’s only a dash in the place of the right so this means read access but not right and same for the other at the end here and if we look at the next line there is the same uh format but this time there is read write for the user and read for the other two then additionally we have this lone lonely d right here uh and that only means that this is a directory and often you will uh be able to identify that because there’s a either a zero on the size or a or the same number for every directory plus you can see this slash at the end in some implementations and configurations of the ls command okay and about targets now we’re coming to the last part of this uh episode change mode change mode is the command for altering permissions on a Unix and Linux system and you do change mode and then something and then the file name like test.txt but what do you type in the middle right here well let’s say we want to give those permissions for the files that we see right here so read write for the owner and read for the other two then we have uh a couple of options we may construct a string which looks like this U equals read write group other equals read so if you put this string in the middle here then you will get those permissions that’s one way another way is to give all the read permission and then the user will add the right permission so this is a plus u+ W so there is the a lot of possible ways to define those groups if you just do if you leave out the A and the U Etc and just do plus read right then it applies to all three groups and you can also do a equals nothing to remove all the permissions I do that sometimes so I run this command and then I specify like group plus r or something like this okay that is one way which is good to use when you are setting permissions that is not very common but if you are changing similar permissions like often there are there is an easier way and that is using numbers so now we come to this 7 five five stuff what does 755 mean well the first number is user this is the group and this is other and if we go back to the first is slide right here if we combine the four and the two and the one then we get a seven which means that seven is read right Axis and the five well there’s only one way to construct the five and that is one and four of course so read and access that is five so this command means that the user will have read write group other will have no the user will have read write access and the group and other will have read and access that’s correct so 755 is something you use a lot because you want to give access to directories and er run permissions for scripts and uh programs and another one which is very common is the 644 that means us sir read right group other read that is usually what a regular file will have will have by default the directories most commonly have the 755 by default and finally another number which I use often on home directories is 700 which means I am the only one with any permissions to even access my home directory what have we learned to today you have learned about Linux file system security that there are three parts to it the file permissions targets and the change mode command let me say a couple of words about the change own by the way as you might have guessed the change own command changes the owner of a specific file so let’s say there is a user called user 5 and you want to give them the ownership of a directory then you do change own us Sur five and then the directory like Etc or whatever if if you want to give a specific group as well then you add a colon and then you type the name of the group so if you have a group called users you will type user five colon users today you have also learned about the read and write and access permissions and uh they flag and numeric and binary representation and what how you can make use of all of these combine them in infinite ways you have learned how to use the ls command to check the permissions and what these different characters mean you have also learned about the three targets the user the group and the other which uh you are able to set permissions for for any file or directory in the system and finally you have learned the change mod and the change own commands which changes the file and directory permissions and the owner respectively okay guys this was a new format using my I P to draw those things I think this is a good format for these kind of videos uh let me know what you think in the comments and uh more c videos are coming up so please subscribe by clicking the little little red button on the bottom right on your screen if you want to Subs subscribe and uh thanks for watching and thanks for today okay so how will our file uh encryptor work well we’re going to create an out file which consists of the first two bytes is a random number between 1 and 65,536 then we will have some padding so if we have the random number 500 then 500 bytes of random bites will follow then we have a 100 a 256bit hash value which will be our hashed uh password or or hashed encryption key that’s so we have an ability to check if we have supplied the correct password or not and then after that all the contents of the file and all of this will also be encrypted using the same key as is hidden in the Sha hash and if you want to know how this works and why I need to do all of this and I have recorded a special episode just for that which I will also link to in the description okay so let’s start [Music] coding as usual I’m going to start by defining the main so I know what functions I need and where when to do them Etc and then I will start filling out the those empty shells with real functions I call it a function signature driven software design okay so let’s include SD IO and all the other ones that I let’s put that in the H by the way so we’ll simply include FS e do H and inside of here we I will put all my regular include files perhaps we won’t be needing all of them and then we can remove them later on but this way we don’t need to pause all the time by looking at and finding these include files string.h and finally we also need our very own arc for. H and let’s create a sign signature for our main in and Char double star like so so how do we want to structure this well we’re obvious is obviously going to need a an arc for instance and we are going to need a key an in file and an out file so sh or let’s use our our own integers so int [Music] 8 let’s make it easy we can convert to our own when we need it so Char and what did I [Music] need in file and out f and we’re also going to need an INF FD and an out FD so that’s a file descriptor that we get from the open Cisco and we’re going to need an int8 for our [Music] key and then we need a couple of sizes at least we need the size of the key so let’s do an in 16 key size like that okay so if r c is less than how many do we need one two is less than three then we’re going to print to standard error and tell that the usage of our binary file is in out and the first is arv and that’s all there we go I hope it the text size isn’t too too small for you and then we’re simply going to return mine as well and now that we have enough arguments we can assign our in file to rv1 and now out file to RV two little bit easier to handle so we don’t have to remember which these are next step is asking for the key or or let’s open the file in file first because because we want to abor early if we don’t if we’re not able to do that so in FD equals open and we’re going to supply the INF file and we’re going to do read [Music] only like this and if infile is less than one F print f stt unable to no let’s not let’s just do print error open and return minus one okay so now the in file is open let’s do the same with the out file by the way so out FD equals open because the file may already exist with the wrong permissions or be badly formatted Etc so let’s open both out file and this is O right only and we also need all create so we create uh the file if it’s not there already and we also need permissions for the file and that’ll be 0 0 600 so only our user will be able to read and write that file and if this open operation fails then FD will be the less than one and in that case we want to close our [Music] NFD and then we’ll do the same as before let this okay so now both our files are open let’s read the key so [Music] key Let’s see we need to have a function which reads both the key and the size of the key right but since we are reading the input from the keyboard we can just do a string length on it we need to improve this when we do our much more secure version in the future sometime okay so key equals read key and uh maybe we’ll Supply some kind of a [Music] prompt key like so and in this case I will do an insert so we also need to include all the sech stuff and that is basically two things we need to [Music] include insert. H and we need to Define G Source if we don’t Define the new source course the assert uh function will still work but another function which is assert P error will not but if we have that definition at the top of our H file everything will work perfectly fine okay let’s see in 6 no the it should be an int8 pointer which we called read key [Music] and in8 here as [Music] well so we need to basically read the key from the keyboard and um uh don’t Echo the characters to the screen so let’s see we’ll wait a little bit with that we’re going to set our what did we call the [Music] key key size key size will be equal to the int [Music] 16 of string length key well let’s do Char like so and then we can change our key to in8 okay so we have read the key next step is to start reading from the uh standard no the next thing is to start writing to the file and the first thing is those two byes of the padding length which will be completely random using a secure Rand function so we need that secure Rand function so let [Music] us let’s create an in8 Let’s see we need to have let’s do in6 and we will call it [Music] the padding length pad size and the actual padding will be stored inside of that in 16 right yes and we need an INT 8 array for the um actual padding bites like so so basically we will do something like pad size or pad size equals [Music] secure round and we need two btes something like that P size [Music] I’m not sure if that’s the best way though it’s a little tricky to store these kinds of data well how do we store it because we’re going to need it for an in6 like this but also for a long string of characters I think we’ll do two different variables this must be the easiest way so let’s say we have an INT 16 called pad size 16 and we also have an INT 8 which is the pad size [Music] eight that should be it so pad size 8 will be equal to this and pad size 16 will be able will be equal to let’s see we need pad size eight D referenced so let’s have um it’s a lot of variables for the same thing this can probably be done much better but I don’t care right now I just need something that works works so pad SI 16 equals the in 16 version of pad size 8 and the actual pad size will be pad size 16 the referenced that should be it right think we need to print this out to see if it really works P size perent [Music] d and this will be the in of pad size this is a lot of different conversions well let’s see if that works um right okay so the only thing is we have the opening of files this is commented out and then we have this so then we can start with this a secure run thing yeah let’s do that close [Music] NFD close alt FD free pad size eight return zero like so okay so how do we create a secure a cryptographically secure function for generating random random numbers there is actually a system call which is [Music] called if we go into the U random I think there should be yeah get random and that is a system Co so basically it returns the size of a buffer of a specific size so if we say that we need eight bytes of random data we get that perhaps or we get less that depends on the entropy pool so basically the the this function uses a lot of different signals like what has occurred since the computer booted up all of different things it puts in a a big pool which is called the Anri pool so you can only create a finite uh amount of these random bites between all all the the whole system and when you run out of entropy you have we just have to wait so you can call this function with two different flags first we’re going to call it with give us all that you have and exit if you don’t have enough and uh if we don’t get all the BS then we will call it again but we will put a message to the user that this may take longer than usual and then we’ll call it without flag well the alternative is that we don’t use a cryptographically a secure version of this and I want it to be un Hackle so this is the stuff we’re going to use this random which means that it doesn’t use a pseudo random function which is not good enough for cryptography so we need to supply the random and then it relies on the ENT trippy pool and basically we will let it be nonblock the first time around and uh the second time without the non block is says Pi so uh size return value and we have the buff and the [Music] size and I think we can supply a Nole buffer to get it on the Heap or perhaps not never mind let’s allocate that ourselves and where is this CIS random. so let’s go into our H file and include sis random. and let’s see this will return in 8 array and we called it secure round and we just need to send number of bytes let’s do in 16 and let’s create this function so int8 array and secure round we will have an n16 size and we need to have an in8 pointer let’s start by checking the size length so we need to assert that size is bigger [Music] than zero [Music] and yeah that’s basically it P will be equal to and in 8 my of size byes we will assert [Music] P or by the way let’s not assert P if yeah let’s a SE p if we run out of memory so Malu will start to fail everything will fail anyway so okay so now we have our buffer we need something that catches the return [Music] value size [Music] and will be equal to get Rand get random and it will be P perhaps we need to no we probably don’t need to type test that and and then the number of bites that size maybe we need to type cast this to a size T and we need the flags right so this and then we have the same but non block so we need it to be random and we need to be non blow so this may return let’s do if n equals size then everything is okay and we can return p and if n is less than zero something has gone wrong and we need to return zero else it means that we did not get enough bytes which means we have to run this again so we do F print F STD L warning pool is empty this may take longer than usual something like that and then we call it again n equal get random and this time we need to Incas incase pointer p+ = n so we will supply p and this time this value will be size minus the N bytes that we have already gotten right and we need to supply the gr R [Music] ND uh random but not non block there we go and if n equals sides [Music] return we need to D allocate by the way and yeah then we need to save a copy we can’t free it if we have jumped it around well we can just jump it back that’s better actually no we don’t need no how many B okay let’s do it this way no hesitation so if n equals size then we return start if n is less than zero then we will free start and return zero and in all other cases it has failed again so we can simply do else here instead and this should be our function so if we call it with two bytes like this and everything is okay we should get different result each time let’s see if this even compiles nope but when does it ever first time in main second argument of main should be sh star star what did I do ah forgot one star we can’t make the main a single star there we go one G couple more to go right open did you mean pop po p open no I did not me me P open that’s a library called for nbes let’s see open what do we need man two open what do we need Okay so let’s include this FC and whatever if INF file is less than one comparison between pointer and integer in file uh where is it if in file if in [Music] FD in [Music] FD alt FD this one was right inate padding unus us variable key size set but not used warning unused variable but it’s compiled so let’s see what happens [Music] F yeah we need to mock these files let’s just touch in file and let’s do FC in file out file 45 938 40 950 yeah this works perfectly well great okay guys let’s create the read key function which will be a quite simple function it’s going to read the key from the keyboard and uh the only thing we have to make sure is that we don’t Echo the characters to the screen so the only thing we’re going to have right here is a prompt and what do we need we need a buffer represented by a pointer so so let’s see we’re going to return an int8 so let’s make this an int8 pointer and we’re going to Let’s see we need a temporary buffer on the stack because we don’t really know how many characters to allocate so let’s let’s say let’s do unsigned Char no let’s do Char and let’s say we have a Max limit of 20 48 bytes or that’s a bit much perhaps because the biggest size uh in a 24 the 8bit encryption system is 256 okay so let’s make it 25 five no 256 because as you know this isn’t the index this is the number of um chars that we want to allocate so counting the zero it’s 256 okay so let’s begin by write writing the naive version of it that Echoes to the screen and then we will simply uh fix that after words so how do we do with this we don’t have to make it so difficult let’s just begin mem setting shouldn’t call this AR buff we’re going to M set the buffer with 0 256 of those then we are going to to read from standard in standard out standard from standard input into our buffer and we have to no we don’t have to cast that and we’re going to read a maximum of 255 so we have room for the ending zero as well okay so now we have read one line we need to remove the ending new line from the input as well and we’re going to need an in for our Let’s do let’s do an in32 for our length know why should we do as big as that an in h right so size and we’ll simply just call string length on the input and then we will let’s see if we have AB b c d that’s the length of four and the indices will be 0 1 2 three and if we have a new line at the end this would be index 4 and the size will be five so let’s do an index as well and index will be the size minus one so let’s do let’s Point our pointer towards uh buff plus uh index and let’s zero that out like [Music] so and then we will allocate our buffer so this will be an in Mal size and if my look fails everything will [Music] fail and if it works we will simply copy our [Music] string to p and from buff and the size will [Music] be size right or maybe minus one by the way just to make room for everything um okay let’s remove this and did I forget anything yes we need to type cast a little bit so the size is an in8 so we need to make this in8 no right an in8 like this and we need to send the bu we can send the buffer as he is read buff no set buff take my look going to string copy to P from buff I think this will work right perhaps we need to cast this one and then we’ll simply return P we also want to print our um prompt let’s not forget about that so let’s do um print F and then our prompt and the space and we get the prompt right here and then we need to flush the buffer because we are not ending the printf line with the new line so we need to flush it manually standard out like so and here is our first version of that code did we create our uh yes but we didn’t make this an int8 this should be a Char okay so let’s let’s try it out without the echo with the Echo and where are we key equals read key thir key yeah let’s try it so [Music] make okay what is it differ in signedness P = buff plus index so it’s this line so P equals buff which is a Char so we need to do in a star plus index don’t think that will be a problem and PS let’s try it out okay we got a got a binary yeah okay so let’s try it out infile out file key AB c d uh we still have that pad size thing we can remove that but it seems to work okay guys uh let’s end there for today and we will continue this uh project another day don’t forget to like And subscribe and thanks for watching and thanks for today [Music] let’s that so print the PAD size let’s just delete that okay okay guys so now that we have our key retrieval function we will need to improve it a little bit and remove the echo of the keyboard characters from the screen so in order to do do that we need to use a function and that is located in an in a header file which is called the termal uh dot h and let me see if there are any examples let’s see okay so there doesn’t seem to be any examples but what we need to do is first because they’re in a terminal there are a couple of options that defines how the terminal should work so we need to do two function calls we need to retrieve the uh current options of your terminal uh then we need to alter one of the flags to remove the Echo and then we will uh do another call to change the flags so that’s how we talk hle the Echo and then we will just call our own function twice once for removing the Echo and once for uh getting the echo back so let’s see let’s begin by importing that H [Music] file it is called termal Doh we also need to create a function let it be a void function that we can call toggle Echo and we don’t really need [Music] any parameters like so so if the echo is enabled we remove it and if it is disabled we put it back uh perhaps we [Music] should yeah this will be easier let’s do a change Echo instead and then we will take a [Music] bull which will say if the echo should be enabled or disabled so we need to include the stdb as well like so so let’s write the function and this will be a void function that we call change Echo and we’ll have a bull enabled like this okay so the next step is we need to create a structure an instance of a structure uh for this kind of stuff and let let me see which one it is uh we’re going to use these two functions which means we need a struct terminals [Music] so let’s see and I closed the window let’s go into our directory it is called FS right no it’s inside temp FSE there we go okay so first I need to reset the home directory like that and we need a stct terminals T and let’s allocate some memory for it t equals stct [Music] terminal size of stct terminals like so let’s copy both of these function signatures to make it a little bit easier to to use them so first we call this get attribute so TC get attribute and the FD follows the same logic as standard in standard out standard error so this should be zero get attribute and then we have the T and that’s basically it perhaps we need to send a reference to the T let’s see if it works or not and let’s see what flag we need to alter I think it’s called Echo there’s a couple of them I think we just do the the echo okay so we need to do a binary operation so basically T is equal to no T the reference is equal to Let’s see we need to do um we need to remove a flag so we will do a logical and operation and that might seem a little bit in nonintuitive but basically if we have X and Y and we let one of them be zero then this will be zero as well if we use the uh or it would still be one so we remove Echo and now now way to we need to do an if first so if enabled then we’re going to add the flag no if it is enabled we’re going to remove it like we did and if it’s if it is disabled we want to enable it or what is most intuitive perhaps we should treat this enabl as if it should be enabled or not so if it should be enabled then we should do the or operation and remove the echo else we do the and operation and then we basically do the other one TC set attribute and we give the file descriptor in optional actions I think we can do the zero there and and then we need to give the structure construct terminals terminals yeah and that’s it so let’s see if this works in our not this one in our read key we will send the prompt then we going to do change Echo and we want to remove the Echo and then we will do it again change Echo and this time we want it to be enabled are true should be false up there right okay let’s see what [Music] happens make okay invalid upun to Binary or yes of course we don’t do it on the the whole structure we need to do it on one of the uh Fields inside that structure so let’s see which it is uh input modes output modes control modes so should either be the could be any one of these let’s see if we search for Echo and we go upwards to the headline C flag flag constraint constants okay so the same flags are for all of these or what did it say C flag okay let’s try it on the C flag it’s tough to remember all of these different functions that you only use once every couple of years let’s see where were we here so this looks right but we’re going to do T C flag and T C flag like so oh not TC flag it should be C flag only so right c c flag all a pointer we need the arrow not the dots let’s try it again TC UND declared T C flag okay now what invalid type argument un star have TC flag F AKA unsigned [Music] in well we should should probably not do reference that word where are we let’s do it like this okay so now we only have one error left has no member named C flag uh it’s tough to get this right huh it should be C FL see FL right let’s double check this time c i flag CC flag let’s copy this instead so remove the whole thing paste this in remove the whole thing paste this in this time I’m feeling lucky okay let’s try out we have infile we’ll have out okay didn’t really work Why didn’t it work perhaps it’s because of this zero or maybe they want us to do this on the standard out because logically it could really be either one right [Music] so make let me try it [Music] again nope Let’s do an S Trace it runs the command so let’s see the first time where is the first time here we get the flags and it has the echo then then we set the flags and do we have the echo no well yes it’s still there what is that let’s see [Music] so oh I forgot to free that one as well but that’s not the cause of the error let’s see so we get the flags if enabl and it’s should be [Music] false the first time read key change Echo false yes so so T see oh I mixed them didn’t I if it should be enabled we or if it should be disabled we end okay so let’s put this this way instead and let’s go back to the [Music] zero let’s try it again in file out file no let’s try it on standard out then so [Music] one one [Music] perhaps we shouldn’t do it on the C flag the other one what what did it say one has to do with input and one has to do with output input modes output mode is this an input mode or an output mode an echo well it’s both well let’s try it with an i input mode on the standard input so I flag and I flag if it should be enabled we add no we had this right the first time and we want to do it on the standard input the standard input okay something happened I can’t press enter anymore that’s pretty weird so we did change it somehow but not really the way I intended so let’s do the let’s just try one thing if we do one here and we do it on the I [Music] flag same thing so let’s do the I flag on [Music] the [Music] zero no for okay so get attributes file standard input okay so now I looked it up we should do it on the standard input as we thought but we should do it on the L flag so let’s try it [Music] again in file out file okay that’s bit weird no that’s not right either okay guys uh let’s end there for today and we will continue this uh project uh another day don’t forget to like And subscribe and thanks for watching and thanks for today [Music] sup guys welcome to Today’s Show today we are going to code a a safe string library and what is a safe string library and what why is it needed well if we let me show you an example so let’s say we have a main and I’m not going to do any error checking now so I will simply take the argument If This Were production code I would of course do a check so we don’t oh so we so we don’t access U parameters and command line arguments that’s not there uh let’s create a string let’s call it St uh and let it be eight in size and then we will create let’s do just a Char pointer and I will let it be equal to hello like this and I will include two files standard IO and the string Library like so okay so I want to put this uh P string into the Str Str variable so then I use string copy and the target is s Str and the source is p so this will copy the contents of P IE this hello and put it into our Str Str and then I will simply print F this Str Str like so and return zero okay let’s compile this and we run it no problem there [Music] right let’s oh sorry I’m going to use Nal today so you get a syntax highlighting uh okay so let’s instead well let me do like this if RC is less than two return minus one just a simple check and we’re going to take one argument from the standard input so instead of doing P equal hello I’m going to do p equal rv1 so we take the first command line uh argument we compile again and if we run it without any AR nothing happens what if we were to do the hello string again then it chose but what if we were to do something bigger than eight like this segmentation fault the program crashes why does this happen well these variables are placed on a stack if we and we don’t we only have room for eight characters in this variable so if we copy a lot of those with a string copy it will start to overflow the stack so basically it may over write variables in this case though the S strr is on the top of the stack so it will start uh overwriting other things like return addresses and saved stack pointers and other important stuff which basically means that the program will will not know how to how to return from this function and it will jump into some memory address which is not right and it will crash so a lot of when you’re dealing with strings a lot of the work is to make sure this doesn’t happen one possible solution to this is that instead of using the string copy like this you add an n in the middle so string n copy because then you can add a third argument which is uh the biggest number of characters to copy so if I put seven in here it can never copy more than seven characters so let’s try this again hello still works and if we do this now it will only do the first couple of characters and then exit without an error so if it’s this easy to fix this problem why bother with it why make a video about save string Library well this is only one example A lot of the times you don’t use functions like this you edit the strings yourself or what if you need to read all the lines in a file for example and put it inside of a string variable how would you do that you need to allocate and reallocate memory so you have the correct amount of memory all the time so it’s it’s not that straightforward to create a safe library for this okay so my plan is to make something that will work like this so let’s let’s remove stuff in here so I want to do something like this I want to create a string so this is my own uh variable and I will initialize Str Str with some initialization function like let’s call it in it and and it will take what will it take it will take a string to begin with so the first first string to put inside of this Str Str variable let’s say hello like so and I will not use any uh numbers so nothing like this that will only need five characters Etc I want to make this a library as easy to use as possible and what we wanted to add like hello the word there so it’s hello there then we can use a concatenation function so we just provide the string a variable name and then what we want to add to that uh string so let’s say uh there and then it will automatically take care of allocating the memory necessary in order to add this to the string and and if we want to print this string to the screen we can do this by just referencing uh let’s say well let’s call it fold and then we just give Str Str and it will will print the contents to the screen and then we only need some kind of um un initialization function so let’s say un init Str Str so we can easily use this conat inside of a loop and read an entire file it can be a very big file gigabytes or even larger and it will put it inside of this string construction that is the plan anyhow let’s see if we manage to do this I’m going to clean up a little bit here and create a simple make file so what do we need we’re going to have a file called Save St str. o which depends on Save S.C and we want to compile it using let’s see dollar roof or carrot or I’m not sure what how to pronounce it this means the source the C file in this case and this means the target the O and we’re going to do d c and yeah let’s not over complicate stuff that’s good and then we will have the safe string s o which depends on safe stram do o and then we will run CC and the source d o and this will be the [Music] Target and now we need a couple of options and I don’t have them in my head right now so I will use a variable which I call options which I will put some content into later on and when we do all I want to First clean and then make a safe St Str doso and finally I will put in the clean which will remove all the dot o files and the dot s f so something like this so if I just do touch and um let’s [Music] see save S.C I should be able to do make and it creates the we do get an error here but that’s only because we we have empty files this far make clean and it’s gone we also need a save st. H and I’m going to create a new window I’m going to go into code and save string I’m going to create set my home directory to this directory and then here I’m going to open the H file and in V save s str. h Save St Ag and then here I’m just going to open the cile so save s str. CC and we going to include our save s str. h like so and as usual I will Begin by defining my main so we’ll see what I want this to do so let’s create a string which we’ll call Str we’re going to initialize it like before using an init function which we hasn’t made yet and we will put in hello and then we want to concatenate yes are with the word there and yeah let’s do something like that to begin with anyway and then we want to un it St Str and in between we want to print it so print F perc s [Music] and fold St Str turn Z okay so this is basically what we want to achieve okay the first thing I’m going to do is include a couple of libraries just the standard ones so [Music] un htd H [Music] and this STD lib Ed include s. this is quite new by the way you might have to install the latest part of GCC if you want this so This adds native support for booleans [Music] H and I usually include string. H but I’m going to wait a little bit my hope is that I don’t need that and I can re write my own functions for that instead however I do need assert because I don’t want to worry too much with it error handling when I’m doing a video and I also need to do a definition for g source and that is so I get the function assert P error so basically this one function is inside of this file but it won’t be defined unless you define this one and it’s basically a combination of theed function and the P error the print error function which is quite nice I think but then you also need to include the r no number that H like so okay so let’s define our structure our string structure so I’ll call it s string and what do we need inside of this well we need some kind of a counter with so we know how many bytes of contents we have in our structure so let’s make this in unide in and we can call it count and we do also need the buffer the the actual string and this can be done a couple of different ways I could Define it as a Char pointer like this and then I allocate memory to this one but an even cooler way I think is to use a new function in later C versions that you can create a you can create a sh array basically string like uh what we going to call it data and usually you do something like this so you put like 64 so it will have 64 byes in it but if you put a zero in there then you define the variable but you don’t create any space for it which means that you can only do this at the end of the structure so this entire structure will be variable length and we can just increase and decrease the entire structure when we need to handle uh the strings which is kind of nifty I think okay and I will type def this instruct s string to string with capital S I will also create a couple of function definitions we have a main with an I’m not sure if I going to take any arguments but let’s put them here to begin with anyway and what else did we say we want an init function and that in it function will take a string an initial string and we want to return the pointer to a string so our own structure like so and then we want a concatenate function which will take a string pointer and another string and this will return a bull if it was successful or not and we also need an un initialization function but for the time being I think I’m going to do a Mac perhaps I need more intricate uh functionality later on so I’ll change that but for now I will just do this unit X will be 3 x like so so let’s start by creating our init function so it will return a string pointer and it’s called init and it takes a initial string like so and we need a size variable sign in size and size will be equal to length of Str Str so we do also need to Define that uh length function and that will basically be um let’s [Music] see that will basically [Music] be well it will be pretty much the same as the regular Str L right so unsigned in length and it takes a Char array we need an n and and a pointer let’s do the constate here and we create a pointer 4 m is equal to zero and P is equal to Sr we’re going to loop as long as let’s see as long as the thing that P points to is not zero and in each iteration we’re going to increase p and we’re going to increase n and we don’t need anything else no body of this one so I’ll add a semicolon at the end and then I’ll just return n and I want to create a function declaration for that as well so unsigned in length and it’ll take a Char star like so okay so now we have the length of the of the string and since this is the initialization function this will be the first uh string so we don’t have to think too much about it uh I do have however one one additional bite allocated and let’s allocate no so it will be this is how much we need for our string but then we also need the size of our structure which will be struct what did I name it s something s string okay that should be enough memory right so let’s create a string [Music] p p will be equal to string size like so and we do also need to zero this structure so one way of one new way of doing that wait first we need to assert that we p is not zero then we’re going to do a let’s [Music] see p I think it’s something like this P equals this I think you do it like that maybe we need to do reference let’s see if that works okay so we have the empty structure now we want to copy the actual string into there so name copy and into P data we want to copy the string [Music] and um let’s see we need a variable for the length so let’s do an n as well so n and size and we let N be equal to the length of this stram and we start substitute this by L which means we can copy n into the string and then we’ll just return P Okay so so let’s comment these out because we’re not done with them and not this one either with the initialization should be okay and let’s do a printf so we see that it it’s working so percent s and this will be St Str data like so okay let’s see what happens oh assignment discards con qualifier okay so let’s [Music] do I think it should be okay to add the con right here did I have the const here no I didn’t [Music] in we need a constant as well so cons basically means that we cannot write to the to that [Music] argument same here okay so con and maybe we don’t need it there [Music] okay discard con qualifier P equals s r okay we have a typo in the header file let’s see main that should be just in and what did we do wrong here let’s see it’s in the length function I [Music] think n = z p = s r p p++ n++ turn [Music] and let’s see what it’s let’s see what it [Music] said okay it didn’t look like this construct perhaps I need to add some options so it uses the new standard let’s see if we add Das s d [Music] equals m let me see c 2 x and let’s add it here as well SD = C2 X still doesn’t like it perhaps it needs the the space [Music] there expected expression plus [Music] P what if we do the slightly older standard and put a zero in there no still is not like that uh I think I need to type cast that’s probably it so let’s make it so and then I do string like so okay now it works M Copy okay what do we need for that M [Music] CP okay inside of the string. [Music] H let’s create our [Music] own [Music] no safe string let’s see so we have a void pointer and or let’s do Bo instead and we can name it copy it’s going to take [Music] a a void pointer to a destination going to take make a const vo source and the con sign in [Music] n and this function will basically be like this but not exactly but let’s start there anyway so cons Char [Music] P Let’s do let’s do like this so const sh [Music] p uh P source and just char No not Char void and right here we just do void T destination and we do a four [Music] where in X and inside here we set X = to n we set P Source equal to Source P destination equal to destination we’re going to iterate until X is z and and each direction we will increase P Source P source and [Music] p p destination and what are we going to do we’re going to take whatever P destination points to and set it to what P Source Point we can make this a void because not much can go wrong and if anything goes wrong then this program will crash so like so save and we need a function declaration so void copy and we have a void pointer for the destination we have a const void pointer for the source and we have a const [Music] unsigned in like so also we need to change so we use our own function where is our M Copy right here so let’s just do copy okay it’s getting better the referencing okay it doesn’t like the referencing void that’s right okay so let’s go into that file again and let’s let’s change the those pointers to char [Music] instead and let’s typ cast a little bit so so p c is equal to the Char version sour or the Cod Char version and this will be equal to the to the Char version of pest like so okay in main conflicting types that’s right we need to add our arguments in RC Char r or see like so and it compiles it does however compile into a library which is a little bit easy a little bit difficult to um to debug or to try out so let’s alter our make file a little bit and let’s change this this I don’t think we need to change anything else actually okay let’s see what happens segmentation fold okay let’s Trace s didn’t say much and L Trace didn’t say anything let’s double check the code let’s [Music] see save string. c s Str data so n equals length of the string I think we need to try out our two utility functions so we know that they work so we have our length and we have our M Copy let’s start with the length we check the length of a b c d e that should be five right okay no problem with that one so how do we check our mem copy in an easy enough way let’s create two Char buffers so buff one 16 and buff 2 16 and I’m going to string copy into buff [Music] one L and I’m going to then copy into F two from bu one and let’s see 2 three four five six n and then I’m going to print the content of um bu two I’m also going to memet both of them to zero them out like that and I need to add temporarily add [Music] the string Library [Music] set Oh wrong punctuation M there we go hello [Music] you okay so both of these function seem to work so how come my stuff doesn’t s Str equals index and print F St Str [Music] perhaps it’s about null termination yeah that’s probably it so where’s the NIT function how much am I alloc the m + 1 plus size of this so there’s room for the null [Music] Terminator let’s see if I if I create a regular sh pointer [Music] CH pointer Shar pointer should be equal to P data plus [Music] n then that should be a zero it should work I think still [Music] thanful hello take this string and equal length [Music] string size = n + one plus the size of this P equals [Music] string size [Music] P = [Music] stre [Music] zero copy P data the string and what happens if I remove this [Applause] slide okay so that’s where it seg FS down even though the copy function actually works so P data string n and n is the length of the string uh okay I forgot [Music] to I set the x to n and my idea was to decrease it and when it reaches zero we’re done but I only did half of that thought so we should add x- minus here as well all righty then then we probably don’t need this stuff since everything already should be zeroed out there we go yeah now it works as intended good sometimes it’s those small little things that makes you need have to trouble shoot forever okay where were we save string. C the only thing we have left actually is [Music] to is to create the concatenation function right which basically merges one of my strings with a regular string so let’s do this [Applause] and that is a [Music] bull and what did we call it we called it concat and it takes a string pointer as an argument and a const Char Source okay so first we need to calculate the memory consumption and we do need an unsigned in M which would be equal to the length of [Music] source so the size we we can make it in three steps let’s do a current sized as [Music] well so the current size is equal [Music] to the destination strings um count + one plus size of stct s string so the size of the structure and the contents that is a current size and the new size should be equal to the current size plus n the number of bytes we need to concatenate so then we have the new size we also need a pointer string p and let’s see no do really need that yes I think we do so p is equal to string and this time we use re look re look and the old memory segment is the destination yeah it’s a destination and the new memory requirements is the size that will be our p and if P fails we simply return false and if it doesn’t fail then we have the memory we need so now we just need to copy the new string so let’s do it basic like we did before I will create an let’s see I will create a regular CH pointer and that chart pointer should be equal to P data plus [Music] P count so basically it should be equal to the old count we need to increase by the with that so we come to the end of the old segment and that’s where we will uh put the new new date and then we will simply copy to P data no to CP and and what should we copy we should copy the source and how much of it it should be n like so and then we will simply do p count plus equals l so we increase the count and we return true that should basically be it right so let’s go down here I will remove this temporary print F and we’ll add back our concat and right we need this fold as well the fold should simply return the value let’s do it quick H Char Fone and it should take a string as an argument and it should simply return string data easy peasy let’s create the function definition as well so CH fold string star and we do have our only knit as well so maybe this compiles let’s see okay what does it say [Music] St St uh it should be S Str right where is it here concat s Str [Music] there uh we should add the serum but at the end when we [Music] conat so let’s [Music] see so CP should then be equal to P data plus the new P count and let’s zero that one like so compiles hold your breath almost it’s it’s showed the there but it didn’t it overwrote our old data I think I know why if we go to the emit function we don’t really increase the initial length so P count should be equal to l that’s right n + [Music] one yeah okay let’s try this again hello there okay so what have we learn today we have learned how to successfully create a a safe string library with a concatenation feature and uh some other stuff and I will leave as an exercise to you to create an equal function that you can use in order to check if two strings are equal and it should work with our string data type and regular strings in any combination if you like this content please like And subscribe there will be a lot of more uh see videos both beginner level and very Advanced I have a lot of interesting stuff in the pipeline so thanks for watching and thanks for [Music] today okay guys welcome back last week we began creating this taly tool which uh tunnels any Linux application through the tour Network we wrote the first part of it which is a socks version for client so this is what we have this far we can supply the destination host and Port so let’s take my web server as an example so we run talize and let’s do this IP with a port of 80 and we connect to the proxy maybe it’s a okay there there we go sometimes when you use the T Network it’s quite slow but more often than not it’s quite fast but as you can see we connected to the proxy we successfully connected through the proxy to the destination and we communicated with the web server on the other end so the biggest part is done what we need to do now is the following we need to turn the client into a library so instead of using an as an application we want to have it as a library and that is a shared library to be specifico files when we have done that we’re going to turn main into our own connect replace regular connect and we’re also going to save a reference to to the original connect so that we can use it ourselves because our current tool is using connect if we look right here so we connect to the proxy server using that uh system call and that’s why we need to save a reference to it so we can use it ourselves um we also need to grab the IP and Port from original connect so we will take care of the arguments that the uh application sends to its connect and and uh we need to take the IP and Port from there instead of reading it from the command arguments like we do now uh and then we can proceed by doing what we do now and then we will just uh leave it to the original application to take care of the uh the rest of the communication so we do our thing and then we exit our fun and let the program take over um okay so how does this technique work well when you compile your code you have two options you can compile it statically so it’s statically linked uh and that means that if you use any Library calls or system calls too for that matter like uh print F or anything that will be that code the print F code will be saved in your program’s uh executable file but that’s not very optimized because if every tool on the on the whole drive would be statically linked then there will be a lot of duplications because almost every application uses some form of Library calls or system calls so that’s why we have the shared libraries so instead of and that’s what’s usually in use so we have like a database with a lot of with a print F code and with a scan F code and even wrappers for system calls like connect and uh when an end application needs to use any of that code it will collect it from the central repository on the on the disk so that’s how it works the thing is there is a kind of um prioritization order so which we can influence so if there are two functions with the same name which one that’s going to execute is decided by a a list basically and a prioritization order so if we name our own function connect and uh we have compiled this as a shared library then we can make any application use our code AS PRI Priority One and in that way we can intercept and hijack the library call and system because all system calls have wrappers in the libraries okay this will probably be um a little more clear when we have written the actual code tested it and this is not my own invention this technique I am following a website let me just find it C shared Library function hook here it is at our Jordan a so it’s pretty simple actually so put s is a function which basically works like print F but not as it prints a single string on the screen so that’s the one that he uses in his example so as you can see he creates a function with the same name and same signature he creates a function pointer also with the same signature and that is for saving the original put s in this case and then he gets the reference from this dsim uh function so basically you give the rtld next and put and the name of the function and it gives back the memory address where that function is originally uh located in memory and uh then he just does like this so he checks if you send the argument hello world and in that case he hijacks the original pest call and changes the message in other case he just runs the uh original puts with the same arguments so this is basically what we’re going to do we’re not going to have a condition because we are always going to hijack the orig original one we are however going to use the original uh connect function to make our connection to the proxy server and uh then we compile it as a shared Library so there’s a couple of additional switches we use and then we get AO file and then we basically tell the system to use our uh Library instead by this LD preload environment variable so we’re going to create a small uh bash script in our case three lines big and um that’s what we’re going to name talize and uh then we’re going to use that to set the environment variable and run the command and uh yeah that should basically be it so let’s begin let’s start by Gra grabbing the um signature so we do man to connect and just copy this exactly as it is and then we go up to our main and just paste it right here like so and sock FD address l t and we remove this [Music] and so we basically turn our main function into this uh connect function like so and we create a function pointer and if you have watched my episode about function pointers you know that that is done like this I will paste the signature for this original original function once again and instead of connect I will just name this P for pointer I’ll put it inside parentheses and add the star and then then we remove this part so it should be basically like a like a signature function uh declaration and we use this to point to this DL Sims function and let me just see where it’s located so Man 3 DL Sims and if we don’t find it in page three we do page two weum perhaps it’s without the S yeah okay so it’s inside of this DL F cn. so let’s add that to our list of includes and let’s see if if he included anything else only the string so and I need to grab the first argument rtld Dore next and you might ask why um I don’t copy paste and I try to avoid that when possible because if I type this a couple of times I will will probably remember it ring next and the name of the function is connect like this and we initialize the socket but we don’t really or let’s do it like this by the way the the curl application or whichever we use have um already initialized their uh socket but I think it will be easier just to uh pipe those two sockets together okay so let me update the signature here as well so I don’t forget that by the way because we we don’t have any main anymore we just have in Connect it’s in right yes did I do in here yes okay so int connect int construct sock address star Su t uh so we don’t have a main anymore because that’s only for applications and this is not an application this is just a couple of functions which are free Okay so the application runs connect and we don’t need anything any of this and we save this we initialize our socket and uh here we make the connection to the proxy server nothing will change about that but we’re not going to call connect because we would be calling ourselves we will be calling this P the function pointer like so connected to proxy and we need we also need to change our request function uh instead of sending host and Port like we did before let me remove that so we have int s and we don’t have this host instead we need to grab the IP and the P Port from the arguments so this is what how what the application provides we have the socket file descriptor we have the length of this structure and we have the actual structure so I think the easiest way would be to I don’t want to name this address let’s call this let’s call it sock to and S2 instead so s and sock that’s ours and S2 and sock 2 are the the provided by the application so we need to look inside of this and get the data that we need so let’s pass the whole structure of that instead uh as host and Port so we’ll just do so two right here and we need to change the signature for our request function um and that is of type stru sock address [Music] in and star stct sock address in Star and I think we need to do a type cast and send the reference so where were we right here so struct sock address stct sock address [Music] in so to I think we need to do it like this if we get a warning or error we will change it but it should be all right struct address in sock 2 so we send that whole structure to this function and we need to change this as well so that will be struck sock address in let’s call it so no let’s call it sock to so we know what’s what okay so the destination Port we don’t need to do hton s and inet address because it’s already in the network bite order so the only thing we need to do is reference talk [Music] to sin port and for the destination IP so [Music] to S address Source address like so perhaps we need to do some type casting but I don’t think so in this case okay so now we have the correct packet and then we save that then we send that [Music] packet unable Traverse proxy we can keep this for now successfully connected through and this we will not have though so as soon as we are connected we are basically done we don’t want to close the socket we do however want to to pipe our socket with the end applications socket so what does it mean piping well we need to do so everything that’s being sent to S will also be sent to S2 and everything that’s being sent to S2 is being s to us and same with the receives so we basically become the man in the middle and there is a good system call which is called dup two which does exactly that um so it creates a new file descriptor and it will be the the same value as the second argument which means that this will be pretty seamless if we give S2 so D to S S2 and then we return the we forget anything I think we did most of it let’s copy the compilation flags from this [Music] one so we’ll go into our make file and this will be [Music] to.so F pictured LDL okay and I will Begin by removing the talize binary executable because that won’t be necessary okay let’s see what it says if we try to compile this one okay DL Sims it should be DL Sim right here and I enter down a little bit and it runs make again and host UND declared okay that’s the message don’t think we actually need that one where is it uh unable to Traverse the proxy successfully connected through the proxy let’s just say through the proxy enter otherwise we need to convert between Network by order and stuff like that perhaps we can change this later on instead if we want to okay it compiled so how are we going to test this we haven’t really created our bash script we can do that now by the way let’s begin by checking what directory we’re we’re in and the name of this so I’ll just do a copy paste of this directory and I will add thiso file to it so this is the whole path to our library and I will log in as the root user I will go to user bin and I will open up Tora lies and this will be a bash [Music] file so we need to have this interpreter at the top or the hashbang uh okay so let’s export LD pre load to this one and then we want to run the commands because we’re going to run this as talize and then curl or whatever so we need to send everything that’s on the right of this toriz and there is a way to access all the arguments at the same time and I I think it is done like this okay so first we export the LD preload and point it towards our shared library then we do the dollar and I think it’s the at sign which will run all the arguments to this uh script and finally we unset the LD preload like this it’s probably not necessary to unset it because it’s the end of the script but I think it’s looks a little better all right so we save this and give it running permissions toiz and then we test it out and hope that it works so Network technology.org we will try to do talize curl and an HTTP request against this IP address connected to proxy uh couldn’t connect the server let’s try restarting the tour perhaps it’s a bad uh connection that happens sometimes so tour restart okay and then we try it again okay connected to proxy this time it didn’t even give an error message let’s see what this error code 91 is if we go back to the RFC so RFC socks 4 and we go down here request rejected or failed I will try once again to restart the service perhaps we are unlucky with the connection so let’s do like this and then we run toye again at least it’s able to intercept the connect function as we can see by this connected to proxy but it doesn’t really succeed in connecting let’s just see that this one is up and running yes and it’s lessening on Port a right let’s do just like this okay I don’t have tet here let’s run it from from this instead so and tet this 80 okay it’s the server that’s not responding that’s weird post let’s try something else let’s do I think we should be able to do a a regular host name this is a Swedish site that shows uh the IP if you if we do make this work though that’s not going through the tour Network the actual DNS request so the DNS request probably goes outside of the tour Network and then the actual IP uh connection goes through so current connect to server weird does anything work Google see yeah there’s nothing wrong with the routing but we need to try something else what if we do a host on this site and we talize a curl HTTP and this IP instead are we able to connect directly to this one okay that works let’s let look through the code perhaps we did miss something so what happens right here we set this to the regular connect function we initialize a new socket and we connect to the proxy with the proxy port using this connect the regular connect function and and we managed to get connected to the proxy everything is fine this far perhaps something perhaps there’s some problem with where we when we grab the IP address so R request stct sock address in perhaps we should not send the reference what if we were to do like this [Music] instead CD code and to and we need to run make and then we do [Music] host and we do talize H curl HTTP and this IP okay so now it works and we should be able to see the IP here I think somewhere okay it seems that we go through some kind of middle server it probably only works against Swedish IP addresses and we probably don’t come from the Swedish IP through the tour Network we need to try something else what if we were to do F we can test regular first so if we do [Music] host what is my ip.com [Music] we do a regular curl and we get an error code okay we need to send the host name and I don’t think that’ll work but let’s try it again uh so curent or it will work when you do right here but I don’t think we will get a response no let’s just do Google them so host Google go. I’m going do tour allies Cur HTTP and this IP okay that works what if we do a host name does it even try to resolve that yeah it works but as I said be careful by doing that because only the IP connection will be private not the DNS request but as you can see we are able to um Traverse the proxy and we are able to talize any command using this tool so that’s the end of this series I hope you want to sub subscribe and like if you think it’s it deserves it and uh there will be more interesting videos in the future thanks for watching and thanks for today

By Amjad Izhar
Contact: amjad.izhar@gmail.com
https://amjadizhar.blog


Discover more from Amjad Izhar Blog

Subscribe to get the latest posts sent to your email.

Comments

Leave a comment