repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
teddycloud
github_2023
toniebox-reverse-engineering
c
osCreateTask
OsTaskId osCreateTask(const char_t *name, OsTaskCode taskCode, void *param, size_t stackSize, int_t priority) { void *handle; //Create a new thread handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) taskCode, param, 0, NULL); WCHAR wname[128]; MultiByteToWideChar(CP_ACP, 0, name, -1, wname, sizeof(wname) / sizeof(wname[0])); SetThreadDescription(handle, wname); //Return a pointer to the newly created thread return (OsTaskId) handle; }
/** * @brief Create a task * @param[in] name A name identifying the task * @param[in] taskCode Pointer to the task entry function * @param[in] param A pointer to a variable to be passed to the task * @param[in] stackSize The initial size of the stack, in words * @param[in] priority The priority at which the task should run * @return Task identifier referencing the newly created task **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L79-L94
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osDeleteTask
void osDeleteTask(OsTaskId taskId) { //Delete the calling thread? if(taskId == OS_SELF_TASK_ID) { //Kill ourselves ExitThread(0); } else { //Delete the specified thread TerminateThread((HANDLE) taskId, 0); } }
/** * @brief Delete a task * @param[in] taskId Task identifier referencing the task to be deleted **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L102-L115
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osDelayTask
void osDelayTask(systime_t delay) { //Delay the task for the specified duration Sleep(delay); }
/** * @brief Delay routine * @param[in] delay Amount of time for which the calling task should block **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L123-L127
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osSwitchTask
void osSwitchTask(void) { //Not implemented }
/** * @brief Yield control to the next task **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L134-L137
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osSuspendAllTasks
void osSuspendAllTasks(void) { if (!isCritSecInitialized) { InitializeCriticalSection(&critSec); isCritSecInitialized = true; } EnterCriticalSection(&critSec); }
/** * @brief Suspend scheduler activity **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L147-L156
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osResumeAllTasks
void osResumeAllTasks(void) { if (!isCritSecInitialized) { InitializeCriticalSection(&critSec); isCritSecInitialized = true; return; } LeaveCriticalSection(&critSec); }
/** * @brief Resume scheduler activity **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L163-L173
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osCreateEvent
bool_t osCreateEvent(OsEvent *event) { //Create an event object event->handle = CreateEvent(NULL, FALSE, FALSE, NULL); //Check whether the returned handle is valid if(event->handle != NULL) { return TRUE; } else { return FALSE; } }
/** * @brief Create an event object * @param[in] event Pointer to the event object * @return The function returns TRUE if the event object was successfully * created. Otherwise, FALSE is returned **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L183-L197
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osDeleteEvent
void osDeleteEvent(OsEvent *event) { //Make sure the handle is valid if(event->handle != NULL) { //Properly dispose the event object CloseHandle(event->handle); } }
/** * @brief Delete an event object * @param[in] event Pointer to the event object **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L205-L213
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osSetEvent
void osSetEvent(OsEvent *event) { //Set the specified event to the signaled state SetEvent(event->handle); }
/** * @brief Set the specified event object to the signaled state * @param[in] event Pointer to the event object **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L221-L225
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osResetEvent
void osResetEvent(OsEvent *event) { //Force the specified event to the nonsignaled state ResetEvent(event->handle); }
/** * @brief Set the specified event object to the nonsignaled state * @param[in] event Pointer to the event object **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L233-L237
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osWaitForEvent
bool_t osWaitForEvent(OsEvent *event, systime_t timeout) { //Wait until the specified event is in the signaled state or the timeout //interval elapses if(WaitForSingleObject(event->handle, timeout) == WAIT_OBJECT_0) { return TRUE; } else { return FALSE; } }
/** * @brief Wait until the specified event is in the signaled state * @param[in] event Pointer to the event object * @param[in] timeout Timeout interval * @return The function returns TRUE if the state of the specified object is * signaled. FALSE is returned if the timeout interval elapsed **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L248-L260
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osSetEventFromIsr
bool_t osSetEventFromIsr(OsEvent *event) { //Not implemented return FALSE; }
/** * @brief Set an event object to the signaled state from an interrupt service routine * @param[in] event Pointer to the event object * @return TRUE if setting the event to signaled state caused a task to unblock * and the unblocked task has a priority higher than the currently running task **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L270-L274
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osCreateSemaphore
bool_t osCreateSemaphore(OsSemaphore *semaphore, uint_t count) { //Create a semaphore object semaphore->handle = CreateSemaphore(NULL, count, count, NULL); //Check whether the returned handle is valid if(semaphore->handle != NULL) { return TRUE; } else { return FALSE; } }
/** * @brief Create a semaphore object * @param[in] semaphore Pointer to the semaphore object * @param[in] count The maximum count for the semaphore object. This value * must be greater than zero * @return The function returns TRUE if the semaphore was successfully * created. Otherwise, FALSE is returned **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L286-L300
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osDeleteSemaphore
void osDeleteSemaphore(OsSemaphore *semaphore) { //Make sure the handle is valid if(semaphore->handle != NULL) { //Properly dispose the semaphore object CloseHandle(semaphore->handle); } }
/** * @brief Delete a semaphore object * @param[in] semaphore Pointer to the semaphore object **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L308-L316
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osWaitForSemaphore
bool_t osWaitForSemaphore(OsSemaphore *semaphore, systime_t timeout) { //Wait until the specified semaphore becomes available if(WaitForSingleObject(semaphore->handle, timeout) == WAIT_OBJECT_0) { return TRUE; } else { return FALSE; } }
/** * @brief Wait for the specified semaphore to be available * @param[in] semaphore Pointer to the semaphore object * @param[in] timeout Timeout interval * @return The function returns TRUE if the semaphore is available. FALSE is * returned if the timeout interval elapsed **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L327-L338
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osReleaseSemaphore
void osReleaseSemaphore(OsSemaphore *semaphore) { //Release the semaphore ReleaseSemaphore(semaphore->handle, 1, NULL); }
/** * @brief Release the specified semaphore object * @param[in] semaphore Pointer to the semaphore object **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L346-L350
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osCreateMutex
bool_t osCreateMutex(OsMutex *mutex) { //Create a mutex object mutex->handle = CreateMutex(NULL, FALSE, NULL); //Check whether the returned handle is valid if(mutex->handle != NULL) { return TRUE; } else { return FALSE; } }
/** * @brief Create a mutex object * @param[in] mutex Pointer to the mutex object * @return The function returns TRUE if the mutex was successfully * created. Otherwise, FALSE is returned **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L360-L374
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osDeleteMutex
void osDeleteMutex(OsMutex *mutex) { //Make sure the handle is valid if(mutex->handle != NULL) { //Properly dispose the mutex object CloseHandle(mutex->handle); } }
/** * @brief Delete a mutex object * @param[in] mutex Pointer to the mutex object **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L382-L390
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osAcquireMutex
void osAcquireMutex(OsMutex *mutex) { //Obtain ownership of the mutex object WaitForSingleObject(mutex->handle, INFINITE); }
/** * @brief Acquire ownership of the specified mutex object * @param[in] mutex Pointer to the mutex object **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L398-L402
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osReleaseMutex
void osReleaseMutex(OsMutex *mutex) { //Release ownership of the mutex object ReleaseMutex(mutex->handle); }
/** * @brief Release ownership of the specified mutex object * @param[in] mutex Pointer to the mutex object **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L410-L414
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osGetSystemTime
systime_t osGetSystemTime(void) { //Get current tick count return GetTickCount(); }
/** * @brief Retrieve system time * @return Number of milliseconds elapsed since the system was last started **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L422-L426
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
osFreeMem
__weak_func void osFreeMem(void *p) { //Free memory block free(p); }
/** * @brief Release a previously allocated memory block * @param[in] p Previously allocated memory block to be freed **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/common/os_port_windows.c#L448-L452
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiInit
void mpiInit(Mpi *r) { // Initialize structure r->sign = 1; r->size = 0; r->data = NULL; }
/** * @brief Initialize a multiple precision integer * @param[in,out] r Pointer to the multiple precision integer to be initialized **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L51-L57
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiFree
void mpiFree(Mpi *r) { // Any memory previously allocated? if (r->data != NULL) { // Erase contents before releasing memory osMemset(r->data, 0, r->size * MPI_INT_SIZE); cryptoFreeMem(r->data); } // Set size to zero r->size = 0; r->data = NULL; }
/** * @brief Release a multiple precision integer * @param[in,out] r Pointer to the multiple precision integer to be freed **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L64-L77
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiGrow
error_t mpiGrow(Mpi *r, uint_t size) { uint_t *data; // Ensure the parameter is valid size = MAX(size, 1); // Check the current size if (r->size >= size) return NO_ERROR; // Allocate a memory buffer data = cryptoAllocMem(size * MPI_INT_SIZE); // Failed to allocate memory? if (data == NULL) return ERROR_OUT_OF_MEMORY; // Clear buffer contents osMemset(data, 0, size * MPI_INT_SIZE); // Any data to copy? if (r->size > 0) { // Copy original data osMemcpy(data, r->data, r->size * MPI_INT_SIZE); // Free previously allocated memory cryptoFreeMem(r->data); } // Update the size of the multiple precision integer r->size = size; r->data = data; // Successful operation return NO_ERROR; }
/** * @brief Adjust the size of multiple precision integer * @param[in,out] r A multiple precision integer whose size is to be increased * @param[in] size Desired size in words * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L86-L121
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiGetLength
uint_t mpiGetLength(const Mpi *a) { int_t i; // Check whether the specified multiple precision integer is empty if (a->size == 0) return 0; // Start from the most significant word for (i = a->size - 1; i >= 0; i--) { // Loop as long as the current word is zero if (a->data[i] != 0) break; } // Return the actual length return i + 1; }
/** * @brief Get the actual length in words * @param[in] a Pointer to a multiple precision integer * @return The actual length in words **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L129-L147
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiGetByteLength
uint_t mpiGetByteLength(const Mpi *a) { uint_t n; uint32_t m; // Check whether the specified multiple precision integer is empty if (a->size == 0) return 0; // Start from the most significant word for (n = a->size - 1; n > 0; n--) { // Loop as long as the current word is zero if (a->data[n] != 0) break; } // Get the current word m = a->data[n]; // Convert the length to a byte count n *= MPI_INT_SIZE; // Adjust the byte count for (; m != 0; m >>= 8) { n++; } // Return the actual length in bytes return n; }
/** * @brief Get the actual length in bytes * @param[in] a Pointer to a multiple precision integer * @return The actual byte count **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L155-L185
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiGetBitLength
uint_t mpiGetBitLength(const Mpi *a) { uint_t n; uint32_t m; // Check whether the specified multiple precision integer is empty if (a->size == 0) return 0; // Start from the most significant word for (n = a->size - 1; n > 0; n--) { // Loop as long as the current word is zero if (a->data[n] != 0) break; } // Get the current word m = a->data[n]; // Convert the length to a bit count n *= MPI_INT_SIZE * 8; // Adjust the bit count for (; m != 0; m >>= 1) { n++; } // Return the actual length in bits return n; }
/** * @brief Get the actual length in bits * @param[in] a Pointer to a multiple precision integer * @return The actual bit count **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L193-L223
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiSetBitValue
error_t mpiSetBitValue(Mpi *r, uint_t index, uint_t value) { error_t error; uint_t n1; uint_t n2; // Retrieve the position of the bit to be written n1 = index / (MPI_INT_SIZE * 8); n2 = index % (MPI_INT_SIZE * 8); // Ajust the size of the multiple precision integer if necessary error = mpiGrow(r, n1 + 1); // Failed to adjust the size? if (error) return error; // Set bit value if (value) r->data[n1] |= (1U << n2); else r->data[n1] &= ~(1U << n2); // No error to report return NO_ERROR; }
/** * @brief Set the bit value at the specified index * @param[in] r Pointer to a multiple precision integer * @param[in] index Position of the bit to be written * @param[in] value Bit value * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L233-L257
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiGetBitValue
uint_t mpiGetBitValue(const Mpi *a, uint_t index) { uint_t n1; uint_t n2; // Retrieve the position of the bit to be read n1 = index / (MPI_INT_SIZE * 8); n2 = index % (MPI_INT_SIZE * 8); // Index out of range? if (n1 >= a->size) return 0; // Return the actual bit value return (a->data[n1] >> n2) & 0x01; }
/** * @brief Get the bit value at the specified index * @param[in] a Pointer to a multiple precision integer * @param[in] index Position where to read the bit * @return The actual bit value **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L266-L281
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiComp
int_t mpiComp(const Mpi *a, const Mpi *b) { uint_t m; uint_t n; // Determine the actual length of A and B m = mpiGetLength(a); n = mpiGetLength(b); // Compare lengths if (!m && !n) return 0; else if (m > n) return a->sign; else if (m < n) return -b->sign; // Compare signs if (a->sign > 0 && b->sign < 0) return 1; else if (a->sign < 0 && b->sign > 0) return -1; // Then compare values while (n--) { if (a->data[n] > b->data[n]) return a->sign; else if (a->data[n] < b->data[n]) return -a->sign; } // Multiple precision integers are equals return 0; }
/** * @brief Compare two multiple precision integers * @param[in] a The first multiple precision integer to be compared * @param[in] b The second multiple precision integer to be compared * @return Comparison result **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L290-L324
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiCompInt
int_t mpiCompInt(const Mpi *a, int_t b) { uint_t value; Mpi t; // Initialize a temporary multiple precision integer value = (b >= 0) ? b : -b; t.sign = (b >= 0) ? 1 : -1; t.size = 1; t.data = &value; // Return comparison result return mpiComp(a, &t); }
/** * @brief Compare a multiple precision integer with an integer * @param[in] a Multiple precision integer to be compared * @param[in] b Integer to be compared * @return Comparison result **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L333-L346
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiCompAbs
int_t mpiCompAbs(const Mpi *a, const Mpi *b) { uint_t m; uint_t n; // Determine the actual length of A and B m = mpiGetLength(a); n = mpiGetLength(b); // Compare lengths if (!m && !n) return 0; else if (m > n) return 1; else if (m < n) return -1; // Then compare values while (n--) { if (a->data[n] > b->data[n]) return 1; else if (a->data[n] < b->data[n]) return -1; } // Operands are equals return 0; }
/** * @brief Compare the absolute value of two multiple precision integers * @param[in] a The first multiple precision integer to be compared * @param[in] b The second multiple precision integer to be compared * @return Comparison result **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L355-L383
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiCopy
error_t mpiCopy(Mpi *r, const Mpi *a) { error_t error; uint_t n; // R and A are the same instance? if (r == a) return NO_ERROR; // Determine the actual length of A n = mpiGetLength(a); // Ajust the size of the destination operand error = mpiGrow(r, n); // Any error to report? if (error) return error; // Clear the contents of the multiple precision integer osMemset(r->data, 0, r->size * MPI_INT_SIZE); // Let R = A osMemcpy(r->data, a->data, n * MPI_INT_SIZE); // Set the sign of R r->sign = a->sign; // Successful operation return NO_ERROR; }
/** * @brief Copy a multiple precision integer * @param[out] r Pointer to a multiple precision integer (destination) * @param[in] a Pointer to a multiple precision integer (source) * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L392-L419
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiSetValue
error_t mpiSetValue(Mpi *r, int_t a) { error_t error; // Ajust the size of the destination operand error = mpiGrow(r, 1); // Failed to adjust the size? if (error) return error; // Clear the contents of the multiple precision integer osMemset(r->data, 0, r->size * MPI_INT_SIZE); // Set the value or R r->data[0] = (a >= 0) ? a : -a; // Set the sign of R r->sign = (a >= 0) ? 1 : -1; // Successful operation return NO_ERROR; }
/** * @brief Set the value of a multiple precision integer * @param[out] r Pointer to a multiple precision integer * @param[in] a Value to be assigned to the multiple precision integer * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L428-L447
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiRand
error_t mpiRand(Mpi *r, uint_t length, const PrngAlgo *prngAlgo, void *prngContext) { error_t error; uint_t m; uint_t n; // Compute the required length, in words n = (length + (MPI_INT_SIZE * 8) - 1) / (MPI_INT_SIZE * 8); // Number of bits in the most significant word m = length % (MPI_INT_SIZE * 8); // Ajust the size of the multiple precision integer if necessary error = mpiGrow(r, n); // Failed to adjust the size? if (error) return error; // Clear the contents of the multiple precision integer osMemset(r->data, 0, r->size * MPI_INT_SIZE); // Set the sign of R r->sign = 1; // Generate a random pattern error = prngAlgo->read(prngContext, (uint8_t *)r->data, n * MPI_INT_SIZE); // Any error to report? if (error) return error; // Remove the meaningless bits in the most significant word if (n > 0 && m > 0) { r->data[n - 1] &= (1 << m) - 1; } // Successful operation return NO_ERROR; }
/** * @brief Generate a random value * @param[out] r Pointer to a multiple precision integer * @param[in] length Desired length in bits * @param[in] prngAlgo PRNG algorithm * @param[in] prngContext Pointer to the PRNG context * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L458-L495
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiRandRange
error_t mpiRandRange(Mpi *r, const Mpi *p, const PrngAlgo *prngAlgo, void *prngContext) { error_t error; uint_t n; Mpi a; // Make sure p is greater than 1 if (mpiCompInt(p, 1) <= 0) return ERROR_INVALID_PARAMETER; // Initialize multiple precision integer mpiInit(&a); // Get the actual length of p n = mpiGetBitLength(p); // Generate extra random bits so that the bias produced by the modular // reduction is negligible MPI_CHECK(mpiRand(r, n + 64, prngAlgo, prngContext)); // Compute r = (r mod (p - 1)) + 1 MPI_CHECK(mpiSubInt(&a, p, 1)); MPI_CHECK(mpiMod(r, r, &a)); MPI_CHECK(mpiAddInt(r, r, 1)); end: // Release previously allocated memory mpiFree(&a); // Return status code return error; }
/** * @brief Generate a random value in the range 1 to p-1 * @param[out] r Pointer to a multiple precision integer * @param[in] p The upper bound of the range * @param[in] prngAlgo PRNG algorithm * @param[in] prngContext Pointer to the PRNG context * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L506-L538
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiCheckProbablePrimeWorker
bool mpiCheckProbablePrimeWorker(const Mpi *n, int k, const PrngAlgo *prngAlgo, void *prngContext) { bool ret = false; /* keep Mpi numbers initialized outside loop */ Mpi randRange; Mpi num1; Mpi num2; Mpi x2; Mpi a; Mpi rnd; Mpi x; Mpi m; Mpi n1; Mpi sShifted; Mpi d; mpiInit(&m); mpiInit(&n1); mpiInit(&sShifted); mpiInit(&d); mpiInit(&randRange); mpiInit(&num1); mpiInit(&num2); mpiInit(&x2); mpiInit(&a); mpiInit(&rnd); mpiInit(&x); mpiSubInt(&m, n, 1); int s = 0; while (!mpiGetBitValue(&m, s)) { s++; } mpiShiftRight(&m, s); mpiSubInt(&n1, n, 1); mpiSetValue(&sShifted, 1); mpiShiftLeft(&sShifted, s); mpiDiv(&d, NULL, &n1, &sShifted); /* randrange shall go from [2..n-2], so prepare consts for 1 + [1..n-3] */ mpiSubInt(&randRange, n, 3); mpiSetValue(&num1, 1); mpiSetValue(&num2, 2); for (int i = 0; i < k; i++) { /* creates a rand between 1 and p-1, including boundaries. upper bounds already corrected */ mpiRandRange(&rnd, &randRange, prngAlgo, prngContext); /* now just add one */ mpiAddAbs(&a, &rnd, &num1); mpiExpMod(&x, &a, &d, n); if (!mpiCompInt(&x, 1) || !mpiComp(&x, &n1)) { continue; } for (int r = 1; r <= s - 1; r++) { mpiExpMod(&x2, &x, &num2, n); if (!mpiCompInt(&x2, 1)) { goto finish; } if (!mpiComp(&x2, &n1)) { goto LOOP; } } goto finish; LOOP: continue; } /* n is *probably* prime */ ret = true; finish: mpiFree(&m); mpiFree(&n1); mpiFree(&sShifted); mpiFree(&d); mpiFree(&randRange); mpiFree(&num1); mpiFree(&num2); mpiFree(&x2); mpiFree(&a); mpiFree(&rnd); mpiFree(&x); return ret; }
/* https://github.com/cslarsen/miller-rabin */
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L541-L642
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiCheckProbablePrime
__weak_func error_t mpiCheckProbablePrime(const Mpi *a) { uint_t k; size_t n; // Retrieve the length of the input integer, in bits n = mpiGetBitLength(a); // Prime numbers of a size lower than 96 bits cannot be tested by this // service if (n < 96) return ERROR_INVALID_LENGTH; // The number of repetitions controls the error probability if (n >= 1300) { k = 2; } else if (n >= 850) { k = 3; } else if (n >= 650) { k = 4; } else if (n >= 550) { k = 5; } else if (n >= 450) { k = 6; } else if (n >= 400) { k = 7; } else if (n >= 350) { k = 8; } else if (n >= 300) { k = 9; } else if (n >= 250) { k = 12; } else if (n >= 200) { k = 15; } else if (n >= 150) { k = 18; } else { k = 27; } /* hardcoded to tls_adapter's PRNG (╯°□°)╯︵ ┻━┻ */ if (mpiCheckProbablePrimeWorker(a, k, rand_get_algo(), rand_get_context())) { return NO_ERROR; } return ERROR_INVALID_VALUE; }
/** * @brief Test whether a number is probable prime * @param[in] a Pointer to a multiple precision integer * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L650-L720
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiImport
error_t mpiImport(Mpi *r, const uint8_t *data, uint_t length, MpiFormat format) { error_t error; uint_t i; // Check input format if (format == MPI_FORMAT_LITTLE_ENDIAN) { // Skip trailing zeroes while (length > 0 && data[length - 1] == 0) { length--; } // Ajust the size of the multiple precision integer error = mpiGrow(r, (length + MPI_INT_SIZE - 1) / MPI_INT_SIZE); // Check status code if (!error) { // Clear the contents of the multiple precision integer osMemset(r->data, 0, r->size * MPI_INT_SIZE); // Set sign r->sign = 1; // Import data for (i = 0; i < length; i++, data++) { r->data[i / MPI_INT_SIZE] |= *data << ((i % MPI_INT_SIZE) * 8); } } } else if (format == MPI_FORMAT_BIG_ENDIAN) { // Skip leading zeroes while (length > 1 && *data == 0) { data++; length--; } // Ajust the size of the multiple precision integer error = mpiGrow(r, (length + MPI_INT_SIZE - 1) / MPI_INT_SIZE); // Check status code if (!error) { // Clear the contents of the multiple precision integer osMemset(r->data, 0, r->size * MPI_INT_SIZE); // Set sign r->sign = 1; // Start from the least significant byte data += length - 1; // Import data for (i = 0; i < length; i++, data--) { r->data[i / MPI_INT_SIZE] |= (uint64_t)*data << ((i % MPI_INT_SIZE) * 8); } } } else { // Report an error error = ERROR_INVALID_PARAMETER; } // Return status code return error; }
/** * @brief Octet string to integer conversion * * Converts an octet string to a non-negative integer * * @param[out] r Non-negative integer resulting from the conversion * @param[in] data Octet string to be converted * @param[in] length Length of the octet string * @param[in] format Input format * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L734-L804
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiExport
error_t mpiExport(const Mpi *a, uint8_t *data, uint_t length, MpiFormat format) { uint_t i; uint_t n; error_t error; // Initialize status code error = NO_ERROR; // Check input format if (format == MPI_FORMAT_LITTLE_ENDIAN) { // Get the actual length in bytes n = mpiGetByteLength(a); // Make sure the output buffer is large enough if (n <= length) { // Clear output buffer osMemset(data, 0, length); // Export data for (i = 0; i < n; i++, data++) { *data = a->data[i / MPI_INT_SIZE] >> ((i % MPI_INT_SIZE) * 8); } } else { // Report an error error = ERROR_INVALID_LENGTH; } } else if (format == MPI_FORMAT_BIG_ENDIAN) { // Get the actual length in bytes n = mpiGetByteLength(a); // Make sure the output buffer is large enough if (n <= length) { // Clear output buffer osMemset(data, 0, length); // Point to the least significant word data += length - 1; // Export data for (i = 0; i < n; i++, data--) { *data = a->data[i / MPI_INT_SIZE] >> ((i % MPI_INT_SIZE) * 8); } } else { // Report an error error = ERROR_INVALID_LENGTH; } } else { // Report an error error = ERROR_INVALID_PARAMETER; } // Return status code return error; }
/** * @brief Integer to octet string conversion * * Converts an integer to an octet string of a specified length * * @param[in] a Non-negative integer to be converted * @param[out] data Octet string resulting from the conversion * @param[in] length Intended length of the resulting octet string * @param[in] format Output format * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L818-L885
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiAdd
error_t mpiAdd(Mpi *r, const Mpi *a, const Mpi *b) { error_t error; int_t sign; // Retrieve the sign of A sign = a->sign; // Both operands have the same sign? if (a->sign == b->sign) { // Perform addition error = mpiAddAbs(r, a, b); // Set the sign of the resulting number r->sign = sign; } // Operands have different signs? else { // Compare the absolute value of A and B if (mpiCompAbs(a, b) >= 0) { // Perform subtraction error = mpiSubAbs(r, a, b); // Set the sign of the resulting number r->sign = sign; } else { // Perform subtraction error = mpiSubAbs(r, b, a); // Set the sign of the resulting number r->sign = -sign; } } // Return status code return error; }
/** * @brief Multiple precision addition * @param[out] r Resulting integer R = A + B * @param[in] a First operand A * @param[in] b Second operand B * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L895-L933
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiAddInt
error_t mpiAddInt(Mpi *r, const Mpi *a, int_t b) { uint_t value; Mpi t; // Convert the second operand to a multiple precision integer value = (b >= 0) ? b : -b; t.sign = (b >= 0) ? 1 : -1; t.size = 1; t.data = &value; // Perform addition return mpiAdd(r, a, &t); }
/** * @brief Add an integer to a multiple precision integer * @param[out] r Resulting integer R = A + B * @param[in] a First operand A * @param[in] b Second operand B * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L943-L956
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiSub
error_t mpiSub(Mpi *r, const Mpi *a, const Mpi *b) { error_t error; int_t sign; // Retrieve the sign of A sign = a->sign; // Both operands have the same sign? if (a->sign == b->sign) { // Compare the absolute value of A and B if (mpiCompAbs(a, b) >= 0) { // Perform subtraction error = mpiSubAbs(r, a, b); // Set the sign of the resulting number r->sign = sign; } else { // Perform subtraction error = mpiSubAbs(r, b, a); // Set the sign of the resulting number r->sign = -sign; } } // Operands have different signs? else { // Perform addition error = mpiAddAbs(r, a, b); // Set the sign of the resulting number r->sign = sign; } // Return status code return error; }
/** * @brief Multiple precision subtraction * @param[out] r Resulting integer R = A - B * @param[in] a First operand A * @param[in] b Second operand B * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L966-L1004
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiSubInt
error_t mpiSubInt(Mpi *r, const Mpi *a, int_t b) { uint_t value; Mpi t; // Convert the second operand to a multiple precision integer value = (b >= 0) ? b : -b; t.sign = (b >= 0) ? 1 : -1; t.size = 1; t.data = &value; // Perform subtraction return mpiSub(r, a, &t); }
/** * @brief Subtract an integer from a multiple precision integer * @param[out] r Resulting integer R = A - B * @param[in] a First operand A * @param[in] b Second operand B * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1014-L1027
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiAddAbs
error_t mpiAddAbs(Mpi *r, const Mpi *a, const Mpi *b) { error_t error; uint_t i; uint_t n; uint_t c; uint_t d; // R and B are the same instance? if (r == b) { // Swap A and B const Mpi *t = a; a = b; b = t; } // R is neither A nor B? else if (r != a) { // Copy the first operand to R MPI_CHECK(mpiCopy(r, a)); } // Determine the actual length of B n = mpiGetLength(b); // Extend the size of the destination register as needed MPI_CHECK(mpiGrow(r, n)); // The result is always positive r->sign = 1; // Clear carry bit c = 0; // Add operands for (i = 0; i < n; i++) { // Add carry bit d = r->data[i] + c; // Update carry bit if (d != 0) c = 0; // Perform addition d += b->data[i]; // Update carry bit if (d < b->data[i]) c = 1; // Save result r->data[i] = d; } // Loop as long as the carry bit is set for (i = n; c && i < r->size; i++) { // Add carry bit r->data[i] += c; // Update carry bit if (r->data[i] != 0) c = 0; } // Check the final carry bit if (c && n >= r->size) { // Extend the size of the destination register MPI_CHECK(mpiGrow(r, n + 1)); // Add carry bit r->data[n] = 1; } end: // Return status code return error; }
/** * @brief Helper routine for multiple precision addition * @param[out] r Resulting integer R = |A + B| * @param[in] a First operand A * @param[in] b Second operand B * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1037-L1109
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiSubAbs
error_t mpiSubAbs(Mpi *r, const Mpi *a, const Mpi *b) { error_t error; uint_t c; uint_t d; uint_t i; uint_t m; uint_t n; // Check input parameters if (mpiCompAbs(a, b) < 0) { // Swap A and B if necessary const Mpi *t = b; a = b; b = t; } // Determine the actual length of A m = mpiGetLength(a); // Determine the actual length of B n = mpiGetLength(b); // Extend the size of the destination register as needed MPI_CHECK(mpiGrow(r, m)); // The result is always positive r->sign = 1; // Clear carry bit c = 0; // Subtract operands for (i = 0; i < n; i++) { // Read first operand d = a->data[i]; // Check the carry bit if (c) { // Update carry bit if (d != 0) c = 0; // Propagate carry bit d -= 1; } // Update carry bit if (d < b->data[i]) c = 1; // Perform subtraction r->data[i] = d - b->data[i]; } // Loop as long as the carry bit is set for (i = n; c && i < m; i++) { // Update carry bit if (a->data[i] != 0) c = 0; // Propagate carry bit r->data[i] = a->data[i] - 1; } // R and A are not the same instance? if (r != a) { // Copy the remaining words for (; i < m; i++) { r->data[i] = a->data[i]; } // Zero the upper part of R for (; i < r->size; i++) { r->data[i] = 0; } } end: // Return status code return error; }
/** * @brief Helper routine for multiple precision subtraction * @param[out] r Resulting integer R = |A - B| * @param[in] a First operand A * @param[in] b Second operand B * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1119-L1202
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiShiftLeft
error_t mpiShiftLeft(Mpi *r, uint_t n) { error_t error; uint_t i; // Number of 32-bit words to shift uint_t n1 = n / (MPI_INT_SIZE * 8); // Number of bits to shift uint_t n2 = n % (MPI_INT_SIZE * 8); // Check parameters if (!r->size || !n) return NO_ERROR; // Increase the size of the multiple-precision number error = mpiGrow(r, r->size + (n + 31) / 32); // Check return code if (error) return error; // First, shift words if (n1 > 0) { // Process the most significant words for (i = r->size - 1; i >= n1; i--) { r->data[i] = r->data[i - n1]; } // Fill the rest with zeroes for (i = 0; i < n1; i++) { r->data[i] = 0; } } // Then shift bits if (n2 > 0) { // Process the most significant words for (i = r->size - 1; i >= 1; i--) { r->data[i] = (r->data[i] << n2) | (r->data[i - 1] >> (32 - n2)); } // The least significant word requires a special handling r->data[0] <<= n2; } // Shift operation is complete return NO_ERROR; }
/** * @brief Left shift operation * @param[in,out] r The multiple precision integer to be shifted to the left * @param[in] n The number of bits to shift * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1211-L1262
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiShiftRight
error_t mpiShiftRight(Mpi *r, uint_t n) { uint_t i; uint_t m; // Number of 32-bit words to shift uint_t n1 = n / (MPI_INT_SIZE * 8); // Number of bits to shift uint_t n2 = n % (MPI_INT_SIZE * 8); // Check parameters if (n1 >= r->size) { osMemset(r->data, 0, r->size * MPI_INT_SIZE); return NO_ERROR; } // First, shift words if (n1 > 0) { // Process the least significant words for (m = r->size - n1, i = 0; i < m; i++) { r->data[i] = r->data[i + n1]; } // Fill the rest with zeroes for (i = m; i < r->size; i++) { r->data[i] = 0; } } // Then shift bits if (n2 > 0) { // Process the least significant words for (m = r->size - n1 - 1, i = 0; i < m; i++) { r->data[i] = (r->data[i] >> n2) | (r->data[i + 1] << (32 - n2)); } // The most significant word requires a special handling r->data[m] >>= n2; } // Shift operation is complete return NO_ERROR; }
/** * @brief Right shift operation * @param[in,out] r The multiple precision integer to be shifted to the right * @param[in] n The number of bits to shift * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1271-L1319
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiMul
__weak_func error_t mpiMul(Mpi *r, const Mpi *a, const Mpi *b) { error_t error; int_t i; int_t m; int_t n; Mpi ta; Mpi tb; // Initialize multiple precision integers mpiInit(&ta); mpiInit(&tb); // R and A are the same instance? if (r == a) { // Copy A to TA MPI_CHECK(mpiCopy(&ta, a)); // Use TA instead of A a = &ta; } // R and B are the same instance? if (r == b) { // Copy B to TB MPI_CHECK(mpiCopy(&tb, b)); // Use TB instead of B b = &tb; } // Determine the actual length of A and B m = mpiGetLength(a); n = mpiGetLength(b); // Adjust the size of R MPI_CHECK(mpiGrow(r, m + n)); // Set the sign of R r->sign = (a->sign == b->sign) ? 1 : -1; // Clear the contents of the destination integer osMemset(r->data, 0, r->size * MPI_INT_SIZE); // Perform multiplication if (m < n) { for (i = 0; i < m; i++) { mpiMulAccCore(&r->data[i], b->data, n, a->data[i]); } } else { for (i = 0; i < n; i++) { mpiMulAccCore(&r->data[i], a->data, m, b->data[i]); } } end: // Release multiple precision integers mpiFree(&ta); mpiFree(&tb); // Return status code return error; }
/** * @brief Multiple precision multiplication * @param[out] r Resulting integer R = A * B * @param[in] a First operand A * @param[in] b Second operand B * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1329-L1395
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiMulInt
error_t mpiMulInt(Mpi *r, const Mpi *a, int_t b) { uint_t value; Mpi t; // Convert the second operand to a multiple precision integer value = (b >= 0) ? b : -b; t.sign = (b >= 0) ? 1 : -1; t.size = 1; t.data = &value; // Perform multiplication return mpiMul(r, a, &t); }
/** * @brief Multiply a multiple precision integer by an integer * @param[out] r Resulting integer R = A * B * @param[in] a First operand A * @param[in] b Second operand B * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1405-L1418
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiDiv
error_t mpiDiv(Mpi *q, Mpi *r, const Mpi *a, const Mpi *b) { error_t error; uint_t m; uint_t n; Mpi c; Mpi d; Mpi e; // Check whether the divisor is equal to zero if (!mpiCompInt(b, 0)) return ERROR_INVALID_PARAMETER; // Initialize multiple precision integers mpiInit(&c); mpiInit(&d); mpiInit(&e); MPI_CHECK(mpiCopy(&c, a)); MPI_CHECK(mpiCopy(&d, b)); MPI_CHECK(mpiSetValue(&e, 0)); m = mpiGetBitLength(&c); n = mpiGetBitLength(&d); if (m > n) MPI_CHECK(mpiShiftLeft(&d, m - n)); while (n++ <= m) { MPI_CHECK(mpiShiftLeft(&e, 1)); if (mpiComp(&c, &d) >= 0) { MPI_CHECK(mpiSetBitValue(&e, 0, 1)); MPI_CHECK(mpiSub(&c, &c, &d)); } MPI_CHECK(mpiShiftRight(&d, 1)); } if (q != NULL) MPI_CHECK(mpiCopy(q, &e)); if (r != NULL) MPI_CHECK(mpiCopy(r, &c)); end: // Release previously allocated memory mpiFree(&c); mpiFree(&d); mpiFree(&e); // Return status code return error; }
/** * @brief Multiple precision division * @param[out] q The quotient Q = A / B * @param[out] r The remainder R = A mod B * @param[in] a The dividend A * @param[in] b The divisor B * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1429-L1484
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiDivInt
error_t mpiDivInt(Mpi *q, Mpi *r, const Mpi *a, int_t b) { uint_t value; Mpi t; // Convert the divisor to a multiple precision integer value = (b >= 0) ? b : -b; t.sign = (b >= 0) ? 1 : -1; t.size = 1; t.data = &value; // Perform division return mpiDiv(q, r, a, &t); }
/** * @brief Divide a multiple precision integer by an integer * @param[out] q The quotient Q = A / B * @param[out] r The remainder R = A mod B * @param[in] a The dividend A * @param[in] b The divisor B * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1495-L1508
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiMod
error_t mpiMod(Mpi *r, const Mpi *a, const Mpi *p) { error_t error; int_t sign; uint_t m; uint_t n; Mpi c; // Make sure the modulus is positive if (mpiCompInt(p, 0) <= 0) return ERROR_INVALID_PARAMETER; // Initialize multiple precision integer mpiInit(&c); // Save the sign of A sign = a->sign; // Determine the actual length of A m = mpiGetBitLength(a); // Determine the actual length of P n = mpiGetBitLength(p); // Let R = A MPI_CHECK(mpiCopy(r, a)); if (m >= n) { MPI_CHECK(mpiCopy(&c, p)); MPI_CHECK(mpiShiftLeft(&c, m - n)); while (mpiCompAbs(r, p) >= 0) { if (mpiCompAbs(r, &c) >= 0) { MPI_CHECK(mpiSubAbs(r, r, &c)); } MPI_CHECK(mpiShiftRight(&c, 1)); } } if (sign < 0) { MPI_CHECK(mpiSubAbs(r, p, r)); } end: // Release previously allocated memory mpiFree(&c); // Return status code return error; }
/** * @brief Modulo operation * @param[out] r Resulting integer R = A mod P * @param[in] a The multiple precision integer to be reduced * @param[in] p The modulus P * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1518-L1570
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiAddMod
error_t mpiAddMod(Mpi *r, const Mpi *a, const Mpi *b, const Mpi *p) { error_t error; // Perform modular addition MPI_CHECK(mpiAdd(r, a, b)); MPI_CHECK(mpiMod(r, r, p)); end: // Return status code return error; }
/** * @brief Modular addition * @param[out] r Resulting integer R = A + B mod P * @param[in] a The first operand A * @param[in] b The second operand B * @param[in] p The modulus P * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1581-L1592
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiSubMod
error_t mpiSubMod(Mpi *r, const Mpi *a, const Mpi *b, const Mpi *p) { error_t error; // Perform modular subtraction MPI_CHECK(mpiSub(r, a, b)); MPI_CHECK(mpiMod(r, r, p)); end: // Return status code return error; }
/** * @brief Modular subtraction * @param[out] r Resulting integer R = A - B mod P * @param[in] a The first operand A * @param[in] b The second operand B * @param[in] p The modulus P * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1603-L1614
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiMulMod
__weak_func error_t mpiMulMod(Mpi *r, const Mpi *a, const Mpi *b, const Mpi *p) { error_t error; // Perform modular multiplication MPI_CHECK(mpiMul(r, a, b)); MPI_CHECK(mpiMod(r, r, p)); end: // Return status code return error; }
/** * @brief Modular multiplication * @param[out] r Resulting integer R = A * B mod P * @param[in] a The first operand A * @param[in] b The second operand B * @param[in] p The modulus P * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1625-L1636
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiInvMod
__weak_func error_t mpiInvMod(Mpi *r, const Mpi *a, const Mpi *p) { error_t error; Mpi b; Mpi c; Mpi q0; Mpi r0; Mpi t; Mpi u; Mpi v; // Initialize multiple precision integers mpiInit(&b); mpiInit(&c); mpiInit(&q0); mpiInit(&r0); mpiInit(&t); mpiInit(&u); mpiInit(&v); MPI_CHECK(mpiCopy(&b, p)); MPI_CHECK(mpiCopy(&c, a)); MPI_CHECK(mpiSetValue(&u, 0)); MPI_CHECK(mpiSetValue(&v, 1)); while (mpiCompInt(&c, 0) > 0) { MPI_CHECK(mpiDiv(&q0, &r0, &b, &c)); MPI_CHECK(mpiCopy(&b, &c)); MPI_CHECK(mpiCopy(&c, &r0)); MPI_CHECK(mpiCopy(&t, &v)); MPI_CHECK(mpiMul(&q0, &q0, &v)); MPI_CHECK(mpiSub(&v, &u, &q0)); MPI_CHECK(mpiCopy(&u, &t)); } if (mpiCompInt(&b, 1)) { MPI_CHECK(ERROR_FAILURE); } if (mpiCompInt(&u, 0) > 0) { MPI_CHECK(mpiCopy(r, &u)); } else { MPI_CHECK(mpiAdd(r, &u, p)); } end: // Release previously allocated memory mpiFree(&b); mpiFree(&c); mpiFree(&q0); mpiFree(&r0); mpiFree(&t); mpiFree(&u); mpiFree(&v); // Return status code return error; }
/** * @brief Modular inverse * @param[out] r Resulting integer R = A^-1 mod P * @param[in] a The multiple precision integer A * @param[in] p The modulus P * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1646-L1710
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiExpMod
__weak_func error_t mpiExpMod(Mpi *r, const Mpi *a, const Mpi *e, const Mpi *p) { error_t error; int_t i; int_t j; int_t n; uint_t d; uint_t k; uint_t u; Mpi b; Mpi c2; Mpi t; Mpi s[8]; // Initialize multiple precision integers mpiInit(&b); mpiInit(&c2); mpiInit(&t); // Initialize precomputed values for (i = 0; (uint_t)i < arraysize(s); i++) { mpiInit(&s[i]); } // Very small exponents are often selected with low Hamming weight. // The sliding window mechanism should be disabled in that case d = (mpiGetBitLength(e) <= 32) ? 1 : 4; // Even modulus? if (mpiIsEven(p)) { // Let B = A^2 MPI_CHECK(mpiMulMod(&b, a, a, p)); // Let S[0] = A MPI_CHECK(mpiCopy(&s[0], a)); // Precompute S[i] = A^(2 * i + 1) for (i = 1; i < (1 << (d - 1)); i++) { MPI_CHECK(mpiMulMod(&s[i], &s[i - 1], &b, p)); } // Let R = 1 MPI_CHECK(mpiSetValue(r, 1)); // The exponent is processed in a left-to-right fashion i = mpiGetBitLength(e) - 1; // Perform sliding window exponentiation while (i >= 0) { // The sliding window exponentiation algorithm decomposes E // into zero and nonzero windows if (!mpiGetBitValue(e, i)) { // Compute R = R^2 MPI_CHECK(mpiMulMod(r, r, r, p)); // Next bit to be processed i--; } else { // Find the longest window n = MAX(i - d + 1, 0); // The least significant bit of the window must be equal to 1 while (!mpiGetBitValue(e, n)) n++; // The algorithm processes more than one bit per iteration for (u = 0, j = i; j >= n; j--) { // Compute R = R^2 MPI_CHECK(mpiMulMod(r, r, r, p)); // Compute the relevant index to be used in the precomputed table u = (u << 1) | mpiGetBitValue(e, j); } // Perform a single multiplication per iteration MPI_CHECK(mpiMulMod(r, r, &s[u >> 1], p)); // Next bit to be processed i = n - 1; } } } else { // Compute the smaller C = (2^32)^k such as C > P k = mpiGetLength(p); // Compute C^2 mod P MPI_CHECK(mpiSetValue(&c2, 1)); MPI_CHECK(mpiShiftLeft(&c2, 2 * k * (MPI_INT_SIZE * 8))); MPI_CHECK(mpiMod(&c2, &c2, p)); // Let B = A * C mod P if (mpiComp(a, p) >= 0) { MPI_CHECK(mpiMod(&b, a, p)); MPI_CHECK(mpiMontgomeryMul(&b, &b, &c2, k, p, &t)); } else { MPI_CHECK(mpiMontgomeryMul(&b, a, &c2, k, p, &t)); } // Let R = B^2 * C^-1 mod P MPI_CHECK(mpiMontgomeryMul(r, &b, &b, k, p, &t)); // Let S[0] = B MPI_CHECK(mpiCopy(&s[0], &b)); // Precompute S[i] = B^(2 * i + 1) * C^-1 mod P for (i = 1; i < (1 << (d - 1)); i++) { MPI_CHECK(mpiMontgomeryMul(&s[i], &s[i - 1], r, k, p, &t)); } // Let R = C mod P MPI_CHECK(mpiCopy(r, &c2)); MPI_CHECK(mpiMontgomeryRed(r, r, k, p, &t)); // The exponent is processed in a left-to-right fashion i = mpiGetBitLength(e) - 1; // Perform sliding window exponentiation while (i >= 0) { // The sliding window exponentiation algorithm decomposes E // into zero and nonzero windows if (!mpiGetBitValue(e, i)) { // Compute R = R^2 * C^-1 mod P MPI_CHECK(mpiMontgomeryMul(r, r, r, k, p, &t)); // Next bit to be processed i--; } else { // Find the longest window n = MAX(i - d + 1, 0); // The least significant bit of the window must be equal to 1 while (!mpiGetBitValue(e, n)) n++; // The algorithm processes more than one bit per iteration for (u = 0, j = i; j >= n; j--) { // Compute R = R^2 * C^-1 mod P MPI_CHECK(mpiMontgomeryMul(r, r, r, k, p, &t)); // Compute the relevant index to be used in the precomputed table u = (u << 1) | mpiGetBitValue(e, j); } // Compute R = R * T[u/2] * C^-1 mod P MPI_CHECK(mpiMontgomeryMul(r, r, &s[u >> 1], k, p, &t)); // Next bit to be processed i = n - 1; } } // Compute R = R * C^-1 mod P MPI_CHECK(mpiMontgomeryRed(r, r, k, p, &t)); } end: // Release multiple precision integers mpiFree(&b); mpiFree(&c2); mpiFree(&t); // Release precomputed values for (i = 0; (uint_t)i < arraysize(s); i++) { mpiFree(&s[i]); } // Return status code return error; }
/** * @brief Modular exponentiation * @param[out] r Resulting integer R = A ^ E mod P * @param[in] a Pointer to a multiple precision integer * @param[in] e Exponent * @param[in] p Modulus * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1721-L1901
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiExpModFast
__weak_func error_t mpiExpModFast(Mpi *r, const Mpi *a, const Mpi *e, const Mpi *p) { // Perform modular exponentiation return mpiExpMod(r, a, e, p); }
/** * @brief Modular exponentiation (fast calculation) * @param[out] r Resulting integer R = A ^ E mod P * @param[in] a Pointer to a multiple precision integer * @param[in] e Exponent * @param[in] p Modulus * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1912-L1916
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiExpModRegular
__weak_func error_t mpiExpModRegular(Mpi *r, const Mpi *a, const Mpi *e, const Mpi *p) { // Perform modular exponentiation return mpiExpMod(r, a, e, p); }
/** * @brief Modular exponentiation (regular calculation) * @param[out] r Resulting integer R = A ^ E mod P * @param[in] a Pointer to a multiple precision integer * @param[in] e Exponent * @param[in] p Modulus * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1927-L1931
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiMontgomeryMul
error_t mpiMontgomeryMul(Mpi *r, const Mpi *a, const Mpi *b, uint_t k, const Mpi *p, Mpi *t) { error_t error; uint_t i; uint_t m; uint_t n; uint_t q; // Use Newton's method to compute the inverse of P[0] mod 2^32 for (m = 2 - p->data[0], i = 0; i < 4; i++) { m = m * (2 - m * p->data[0]); } // Precompute -1/P[0] mod 2^32; m = ~m + 1; // We assume that B is always less than 2^k n = MIN(b->size, k); // Make sure T is large enough MPI_CHECK(mpiGrow(t, 2 * k + 1)); // Let T = 0 MPI_CHECK(mpiSetValue(t, 0)); // Perform Montgomery multiplication for (i = 0; i < k; i++) { // Check current index if (i < a->size) { // Compute q = ((T[i] + A[i] * B[0]) * m) mod 2^32 q = (t->data[i] + a->data[i] * b->data[0]) * m; // Compute T = T + A[i] * B mpiMulAccCore(t->data + i, b->data, n, a->data[i]); } else { // Compute q = (T[i] * m) mod 2^32 q = t->data[i] * m; } // Compute T = T + q * P mpiMulAccCore(t->data + i, p->data, k, q); } // Compute R = T / 2^(32 * k) MPI_CHECK(mpiShiftRight(t, k * (MPI_INT_SIZE * 8))); MPI_CHECK(mpiCopy(r, t)); // A final subtraction is required if (mpiComp(r, p) >= 0) { MPI_CHECK(mpiSub(r, r, p)); } end: // Return status code return error; }
/** * @brief Montgomery multiplication * @param[out] r Resulting integer R = A * B / 2^k mod P * @param[in] a An integer A such as 0 <= A < 2^k * @param[in] b An integer B such as 0 <= B < 2^k * @param[in] k An integer k such as P < 2^k * @param[in] p Modulus P * @param[in] t An preallocated integer T (for internal operation) * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L1944-L2004
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiMontgomeryRed
error_t mpiMontgomeryRed(Mpi *r, const Mpi *a, uint_t k, const Mpi *p, Mpi *t) { uint_t value; Mpi b; // Let B = 1 value = 1; b.sign = 1; b.size = 1; b.data = &value; // Compute R = A / 2^k mod P return mpiMontgomeryMul(r, a, &b, k, p, t); }
/** * @brief Montgomery reduction * @param[out] r Resulting integer R = A / 2^k mod P * @param[in] a An integer A such as 0 <= A < 2^k * @param[in] k An integer k such as P < 2^k * @param[in] p Modulus P * @param[in] t An preallocated integer T (for internal operation) * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L2016-L2029
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiMulAccCore
void mpiMulAccCore(uint_t *r, const uint_t *a, int_t m, const uint_t b) { int_t i; uint32_t c; uint32_t u; uint32_t v; uint64_t p; // Clear variables c = 0; u = 0; v = 0; // Perform multiplication for (i = 0; i < m; i++) { p = (uint64_t)a[i] * b; u = (uint32_t)p; v = (uint32_t)(p >> 32); u += c; if (u < c) v++; u += r[i]; if (u < r[i]) v++; r[i] = u; c = v; } // Propagate carry for (; c != 0; i++) { r[i] += c; c = (r[i] < c); } }
/** * @brief Multiply-accumulate operation * @param[out] r Resulting integer * @param[in] a First operand A * @param[in] m Size of A in words * @param[in] b Second operand B **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L2041-L2079
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
mpiDump
void mpiDump(FILE *stream, const char_t *prepend, const Mpi *a) { uint_t i; // Process each word for (i = 0; i < a->size; i++) { // Beginning of a new line? if (i == 0 || ((a->size - i - 1) % 8) == 7) fprintf(stream, "%s", prepend); // Display current data fprintf(stream, "%08X ", a->data[a->size - 1 - i]); // End of current line? if (((a->size - i - 1) % 8) == 0 || i == (a->size - 1)) fprintf(stream, "\r\n"); } }
/** * @brief Display the contents of a multiple precision integer * @param[in] stream Pointer to a FILE object that identifies an output stream * @param[in] prepend String to prepend to the left of each line * @param[in] a Pointer to a multiple precision integer **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/mpi.c#L2090-L2108
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
aesInit
__weak_func error_t aesInit(AesContext *context, const uint8_t *key, size_t keyLen) { uint_t i; uint32_t temp; size_t keyScheduleSize; //Check parameters if(context == NULL || key == NULL) return ERROR_INVALID_PARAMETER; //Check the length of the key if(keyLen == 16) { //10 rounds are required for 128-bit key context->nr = 10; } else if(keyLen == 24) { //12 rounds are required for 192-bit key context->nr = 12; } else if(keyLen == 32) { //14 rounds are required for 256-bit key context->nr = 14; } else { //Report an error return ERROR_INVALID_KEY_LENGTH; } //Determine the number of 32-bit words in the key keyLen /= 4; //Copy the original key for(i = 0; i < keyLen; i++) { context->ek[i] = LOAD32LE(key + (i * 4)); } //The size of the key schedule depends on the number of rounds keyScheduleSize = 4 * (context->nr + 1); //Generate the key schedule (encryption) for(i = keyLen; i < keyScheduleSize; i++) { //Save previous word temp = context->ek[i - 1]; //Apply transformation if((i % keyLen) == 0) { context->ek[i] = sbox[(temp >> 8) & 0xFF]; context->ek[i] |= ((uint64_t)sbox[(temp >> 16) & 0xFF] << 8); context->ek[i] |= ((uint64_t)sbox[(temp >> 24) & 0xFF] << 16); context->ek[i] |= ((uint64_t)sbox[temp & 0xFF] << 24); context->ek[i] ^= rcon[i / keyLen]; } else if(keyLen > 6 && (i % keyLen) == 4) { context->ek[i] = sbox[temp & 0xFF]; context->ek[i] |= ((uint64_t)sbox[(temp >> 8) & 0xFF] << 8); context->ek[i] |= ((uint64_t)sbox[(temp >> 16) & 0xFF] << 16); context->ek[i] |= ((uint64_t)sbox[(temp >> 24) & 0xFF] << 24); } else { context->ek[i] = temp; } //Update the key schedule context->ek[i] ^= context->ek[i - keyLen]; } //Generate the key schedule (decryption) for(i = 0; i < keyScheduleSize; i++) { //Apply the InvMixColumns transformation to all round keys but the first //and the last if(i < 4 || i >= (keyScheduleSize - 4)) { context->dk[i] = context->ek[i]; } else { context->dk[i] = td[sbox[context->ek[i] & 0xFF]]; temp = td[sbox[(context->ek[i] >> 8) & 0xFF]]; context->dk[i] ^= ROL32(temp, 8); temp = td[sbox[(context->ek[i] >> 16) & 0xFF]]; context->dk[i] ^= ROL32(temp, 16); temp = td[sbox[(context->ek[i] >> 24) & 0xFF]]; context->dk[i] ^= ROL32(temp, 24); } } //No error to report return NO_ERROR; }
/** * @brief Key expansion * @param[in] context Pointer to the AES context to initialize * @param[in] key Pointer to the key * @param[in] keyLen Length of the key * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/cipher/aes.c#L203-L302
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
aesEncryptBlock
__weak_func void aesEncryptBlock(AesContext *context, const uint8_t *input, uint8_t *output) { uint_t i; uint32_t s0; uint32_t s1; uint32_t s2; uint32_t s3; uint32_t t0; uint32_t t1; uint32_t t2; uint32_t t3; uint32_t temp; //Copy the plaintext to the state array s0 = LOAD32LE(input + 0); s1 = LOAD32LE(input + 4); s2 = LOAD32LE(input + 8); s3 = LOAD32LE(input + 12); //Initial round key addition s0 ^= context->ek[0]; s1 ^= context->ek[1]; s2 ^= context->ek[2]; s3 ^= context->ek[3]; //The number of rounds depends on the key length for(i = 1; i < context->nr; i++) { //Apply round function t0 = te[s0 & 0xFF]; temp = te[(s1 >> 8) & 0xFF]; t0 ^= ROL32(temp, 8); temp = te[(s2 >> 16) & 0xFF]; t0 ^= ROL32(temp, 16); temp = te[(s3 >> 24) & 0xFF]; t0 ^= ROL32(temp, 24); t1 = te[s1 & 0xFF]; temp = te[(s2 >> 8) & 0xFF]; t1 ^= ROL32(temp, 8); temp = te[(s3 >> 16) & 0xFF]; t1 ^= ROL32(temp, 16); temp = te[(s0 >> 24) & 0xFF]; t1 ^= ROL32(temp, 24); t2 = te[s2 & 0xFF]; temp = te[(s3 >> 8) & 0xFF]; t2 ^= ROL32(temp, 8); temp = te[(s0 >> 16) & 0xFF]; t2 ^= ROL32(temp, 16); temp = te[(s1 >> 24) & 0xFF]; t2 ^= ROL32(temp, 24); t3 = te[s3 & 0xFF]; temp = te[(s0 >> 8) & 0xFF]; t3 ^= ROL32(temp, 8); temp = te[(s1 >> 16) & 0xFF]; t3 ^= ROL32(temp, 16); temp = te[(s2 >> 24) & 0xFF]; t3 ^= ROL32(temp, 24); //Round key addition s0 = t0 ^ context->ek[i * 4]; s1 = t1 ^ context->ek[i * 4 + 1]; s2 = t2 ^ context->ek[i * 4 + 2]; s3 = t3 ^ context->ek[i * 4 + 3]; } //The last round differs slightly from the first rounds t0 = sbox[s0 & 0xFF]; t0 |= (uint64_t)sbox[(s1 >> 8) & 0xFF] << 8; t0 |= (uint64_t)sbox[(s2 >> 16) & 0xFF] << 16; t0 |= (uint64_t)sbox[(s3 >> 24) & 0xFF] << 24; t1 = sbox[s1 & 0xFF]; t1 |= (uint64_t)sbox[(s2 >> 8) & 0xFF] << 8; t1 |= (uint64_t)sbox[(s3 >> 16) & 0xFF] << 16; t1 |= (uint64_t)sbox[(s0 >> 24) & 0xFF] << 24; t2 = sbox[s2 & 0xFF]; t2 |= (uint64_t)sbox[(s3 >> 8) & 0xFF] << 8; t2 |= (uint64_t)sbox[(s0 >> 16) & 0xFF] << 16; t2 |= (uint64_t)sbox[(s1 >> 24) & 0xFF] << 24; t3 = sbox[s3 & 0xFF]; t3 |= (uint64_t)sbox[(s0 >> 8) & 0xFF] << 8; t3 |= (uint64_t)sbox[(s1 >> 16) & 0xFF] << 16; t3 |= (uint64_t)sbox[(s2 >> 24) & 0xFF] << 24; //Last round key addition s0 = t0 ^ context->ek[context->nr * 4]; s1 = t1 ^ context->ek[context->nr * 4 + 1]; s2 = t2 ^ context->ek[context->nr * 4 + 2]; s3 = t3 ^ context->ek[context->nr * 4 + 3]; //The final state is then copied to the output STORE32LE(s0, output + 0); STORE32LE(s1, output + 4); STORE32LE(s2, output + 8); STORE32LE(s3, output + 12); }
/** * @brief Encrypt a 16-byte block using AES algorithm * @param[in] context Pointer to the AES context * @param[in] input Plaintext block to encrypt * @param[out] output Ciphertext block resulting from encryption **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/cipher/aes.c#L312-L413
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
aesDecryptBlock
__weak_func void aesDecryptBlock(AesContext *context, const uint8_t *input, uint8_t *output) { uint_t i; uint32_t s0; uint32_t s1; uint32_t s2; uint32_t s3; uint32_t t0; uint32_t t1; uint32_t t2; uint32_t t3; uint32_t temp; //Copy the ciphertext to the state array s0 = LOAD32LE(input + 0); s1 = LOAD32LE(input + 4); s2 = LOAD32LE(input + 8); s3 = LOAD32LE(input + 12); //Initial round key addition s0 ^= context->dk[context->nr * 4]; s1 ^= context->dk[context->nr * 4 + 1]; s2 ^= context->dk[context->nr * 4 + 2]; s3 ^= context->dk[context->nr * 4 + 3]; //The number of rounds depends on the key length for(i = context->nr - 1; i >= 1; i--) { //Apply round function t0 = td[s0 & 0xFF]; temp = td[(s3 >> 8) & 0xFF]; t0 ^= ROL32(temp, 8); temp = td[(s2 >> 16) & 0xFF]; t0 ^= ROL32(temp, 16); temp = td[(s1 >> 24) & 0xFF]; t0 ^= ROL32(temp, 24); t1 = td[s1 & 0xFF]; temp = td[(s0 >> 8) & 0xFF]; t1 ^= ROL32(temp, 8); temp = td[(s3 >> 16) & 0xFF]; t1 ^= ROL32(temp, 16); temp = td[(s2 >> 24) & 0xFF]; t1 ^= ROL32(temp, 24); t2 = td[s2 & 0xFF]; temp = td[(s1 >> 8) & 0xFF]; t2 ^= ROL32(temp, 8); temp = td[(s0 >> 16) & 0xFF]; t2 ^= ROL32(temp, 16); temp = td[(s3 >> 24) & 0xFF]; t2 ^= ROL32(temp, 24); t3 = td[s3 & 0xFF]; temp = td[(s2 >> 8) & 0xFF]; t3 ^= ROL32(temp, 8); temp = td[(s1 >> 16) & 0xFF]; t3 ^= ROL32(temp, 16); temp = td[(s0 >> 24) & 0xFF]; t3 ^= ROL32(temp, 24); //Round key addition s0 = t0 ^ context->dk[i * 4]; s1 = t1 ^ context->dk[i * 4 + 1]; s2 = t2 ^ context->dk[i * 4 + 2]; s3 = t3 ^ context->dk[i * 4 + 3]; } //The last round differs slightly from the first rounds t0 = isbox[s0 & 0xFF]; t0 |= (uint64_t)isbox[(s3 >> 8) & 0xFF] << 8; t0 |= (uint64_t)isbox[(s2 >> 16) & 0xFF] << 16; t0 |= (uint64_t)isbox[(s1 >> 24) & 0xFF] << 24; t1 = isbox[s1 & 0xFF]; t1 |= (uint64_t)isbox[(s0 >> 8) & 0xFF] << 8; t1 |= (uint64_t)isbox[(s3 >> 16) & 0xFF] << 16; t1 |= (uint64_t)isbox[(s2 >> 24) & 0xFF] << 24; t2 = isbox[s2 & 0xFF]; t2 |= (uint64_t)isbox[(s1 >> 8) & 0xFF] << 8; t2 |= (uint64_t)isbox[(s0 >> 16) & 0xFF] << 16; t2 |= (uint64_t)isbox[(s3 >> 24) & 0xFF] << 24; t3 = isbox[s3 & 0xFF]; t3 |= (uint64_t)isbox[(s2 >> 8) & 0xFF] << 8; t3 |= (uint64_t)isbox[(s1 >> 16) & 0xFF] << 16; t3 |= (uint64_t)isbox[(s0 >> 24) & 0xFF] << 24; //Last round key addition s0 = t0 ^ context->dk[0]; s1 = t1 ^ context->dk[1]; s2 = t2 ^ context->dk[2]; s3 = t3 ^ context->dk[3]; //The final state is then copied to the output STORE32LE(s0, output + 0); STORE32LE(s1, output + 4); STORE32LE(s2, output + 8); STORE32LE(s3, output + 12); }
/** * @brief Decrypt a 16-byte block using AES algorithm * @param[in] context Pointer to the AES context * @param[in] input Ciphertext block to decrypt * @param[out] output Plaintext block resulting from decryption **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/cipher/aes.c#L423-L524
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
aesDeinit
__weak_func void aesDeinit(AesContext *context) { //Clear AES context osMemset(context, 0, sizeof(AesContext)); }
/** * @brief Release AES context * @param[in] context Pointer to the AES context **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_crypto/cipher/aes.c#L532-L536
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tlsFormatCertificateList
error_t tlsFormatCertificateList(TlsContext *context, uint8_t *p, size_t *written) { error_t error; size_t m; size_t n; size_t certChainLen; const char_t *certChain; //Initialize status code error = NO_ERROR; //Length of the certificate list in bytes *written = 0; //Check whether a certificate is available if(context->cert != NULL) { //Point to the certificate chain certChain = context->cert->certChain; //Get the total length, in bytes, of the certificate chain certChainLen = context->cert->certChainLen; } else { //If no suitable certificate is available, the message contains an //empty certificate list certChain = NULL; certChainLen = 0; } //Parse the certificate chain while(certChainLen > 0) { //The first pass calculates the length of the DER-encoded certificate error = pemImportCertificate(certChain, certChainLen, NULL, &n, NULL); //End of file detected? if(error) { //Exit immediately error = NO_ERROR; break; } //Buffer overflow? if((*written + n + 3) > context->txBufferMaxLen) { //Report an error error = ERROR_MESSAGE_TOO_LONG; break; } //Each certificate is preceded by a 3-byte length field STORE24BE(n, p); //The second pass decodes the PEM certificate error = pemImportCertificate(certChain, certChainLen, p + 3, &n, &m); //Any error to report? if(error) break; //Advance read pointer certChain += m; certChainLen -= m; //Advance write pointer p += n + 3; *written += n + 3; #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3) //TLS 1.3 currently selected? if(context->version == TLS_VERSION_1_3) { //Format the list of extensions for the current CertificateEntry error = tls13FormatCertExtensions(p, &n); //Any error to report? if(error) break; //Advance write pointer p += n; *written += n; } #endif } //Return status code return error; }
/** * @brief Format certificate chain * @param[in] context Pointer to the TLS context * @param[in] p Output stream where to write the certificate chain * @param[out] written Total number of bytes that have been written * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_ssl/tls_certificate.c#L58-L147
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tlsFormatRawPublicKey
error_t tlsFormatRawPublicKey(TlsContext *context, uint8_t *p, size_t *written) { error_t error; //Initialize status code error = NO_ERROR; //Length of the certificate list in bytes *written = 0; #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED) //Check whether a certificate is available if(context->cert != NULL) { size_t n; uint8_t *derCert; size_t derCertLen; X509CertInfo *certInfo; //Initialize variables derCert = NULL; certInfo = NULL; //Start of exception handling block do { //The first pass calculates the length of the DER-encoded certificate error = pemImportCertificate(context->cert->certChain, context->cert->certChainLen, NULL, &derCertLen, NULL); //Any error to report? if(error) break; //Allocate a memory buffer to hold the DER-encoded certificate derCert = tlsAllocMem(derCertLen); //Failed to allocate memory? if(derCert == NULL) { error = ERROR_OUT_OF_MEMORY; break; } //The second pass decodes the PEM certificate error = pemImportCertificate(context->cert->certChain, context->cert->certChainLen, derCert, &derCertLen, NULL); //Any error to report? if(error) break; //Allocate a memory buffer to store X.509 certificate info certInfo = tlsAllocMem(sizeof(X509CertInfo)); //Failed to allocate memory? if(certInfo == NULL) { error = ERROR_OUT_OF_MEMORY; break; } //Parse X.509 certificate error = x509ParseCertificate(derCert, derCertLen, certInfo); //Failed to parse the X.509 certificate? if(error) break; //Retrieve the length of the raw public key n = certInfo->tbsCert.subjectPublicKeyInfo.raw.length; #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3) //TLS 1.3 currently selected? if(context->version == TLS_VERSION_1_3) { //The raw public key is preceded by a 3-byte length field STORE24BE(n, p); //Copy the raw public key osMemcpy(p + 3, certInfo->tbsCert.subjectPublicKeyInfo.raw.value, n); //Advance data pointer p += n + 3; //Adjust the length of the certificate list *written += n + 3; //Format the list of extensions for the current CertificateEntry error = tls13FormatCertExtensions(p, &n); //Any error to report? if(error) break; //Advance data pointer p += n; //Adjust the length of the certificate list *written += n; } else #endif { //Copy the raw public key osMemcpy(p, certInfo->tbsCert.subjectPublicKeyInfo.raw.value, n); //Advance data pointer p += n; //Adjust the length of the certificate list *written += n; } //End of exception handling block } while(0); //Release previously allocated memory tlsFreeMem(derCert); tlsFreeMem(certInfo); } #endif //Return status code return error; }
/** * @brief Format raw public key * @param[in] context Pointer to the TLS context * @param[in] p Output stream where to write the raw public key * @param[out] written Total number of bytes that have been written * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_ssl/tls_certificate.c#L158-L274
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tlsParseCertificateList_override
__weak_func error_t tlsParseCertificateList_override(TlsContext *context, const uint8_t *p, size_t length) { error_t error; error_t certValidResult; uint_t i; size_t n; const char_t *subjectName; X509CertInfo *certInfo; X509CertInfo *issuerCertInfo; //Initialize X.509 certificates certInfo = NULL; issuerCertInfo = NULL; //Start of exception handling block do { //Allocate a memory buffer to store X.509 certificate info certInfo = tlsAllocMem(sizeof(X509CertInfo)); //Failed to allocate memory? if(certInfo == NULL) { //Report an error error = ERROR_OUT_OF_MEMORY; break; } //Allocate a memory buffer to store the parent certificate issuerCertInfo = tlsAllocMem(sizeof(X509CertInfo)); //Failed to allocate memory? if(issuerCertInfo == NULL) { //Report an error error = ERROR_OUT_OF_MEMORY; break; } //The end-user certificate is preceded by a 3-byte length field if(length < 3) { //Report an error error = ERROR_DECODING_FAILED; break; } //Get the size occupied by the certificate n = LOAD24BE(p); //Jump to the beginning of the DER-encoded certificate p += 3; length -= 3; //Malformed Certificate message? if(n == 0 || n > length) { //Report an error error = ERROR_DECODING_FAILED; break; } //Display ASN.1 structure error = asn1DumpObject(p, n, 0); //Any error to report? if(error) break; //Parse end-user certificate error = x509ParseCertificate(p, n, certInfo); //Failed to parse the X.509 certificate? if(error) { //Report an error error = ERROR_BAD_CERTIFICATE; break; } //Check certificate key usage error = tlsCheckKeyUsage(certInfo, context->entity, context->keyExchMethod); //Any error to report? if(error) break; //Extract the public key from the end-user certificate error = tlsReadSubjectPublicKey(context, &certInfo->tbsCert.subjectPublicKeyInfo); //Any error to report? if(error) break; #if (TLS_CLIENT_SUPPORT == ENABLED) //Client mode? if(context->entity == TLS_CONNECTION_END_CLIENT) { TlsCertificateType certType; TlsNamedGroup namedCurve; //Retrieve the type of the X.509 certificate error = tlsGetCertificateType(certInfo, &certType, &namedCurve); //Unsupported certificate? if(error) break; //Version of TLS prior to TLS 1.3? if(context->version <= TLS_VERSION_1_2) { //ECDSA certificate? if(certType == TLS_CERT_ECDSA_SIGN) { //Make sure the elliptic curve is supported if(tlsGetCurveInfo(context, namedCurve) == NULL) { error = ERROR_BAD_CERTIFICATE; break; } } } //Point to the subject name subjectName = context->serverName; //Check the subject name in the server certificate against the actual //FQDN name that is being requested error = x509CheckSubjectName(certInfo, subjectName); //Any error to report? if(error) { //Debug message TRACE_WARNING("Server name mismatch!\r\n"); //Report an error error = ERROR_BAD_CERTIFICATE; break; } } else #endif //Server mode? { //Do not check name constraints subjectName = NULL; } //Check if the end-user certificate can be matched with a trusted CA certValidResult = tlsValidateCertificate(context, certInfo, 0, subjectName); //Check validation result if(certValidResult != NO_ERROR && certValidResult != ERROR_UNKNOWN_CA) { //The certificate is not valid error = certValidResult; break; } //Next certificate p += n; length -= n; #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3) //TLS 1.3 currently selected? if(context->version == TLS_VERSION_1_3) { //Parse the list of extensions for the current CertificateEntry error = tls13ParseCertExtensions(p, length, &n); //Any error to report? if(error) break; //Point to the next field p += n; //Remaining bytes to process length -= n; } #endif //PKIX path validation for(i = 0; length > 0; i++) { //Each intermediate certificate is preceded by a 3-byte length field if(length < 3) { //Report an error error = ERROR_DECODING_FAILED; break; } //Get the size occupied by the certificate n = LOAD24BE(p); //Jump to the beginning of the DER-encoded certificate p += 3; //Remaining bytes to process length -= 3; //Malformed Certificate message? if(n == 0 || n > length) { //Report an error error = ERROR_DECODING_FAILED; break; } //Display ASN.1 structure error = asn1DumpObject(p, n, 0); //Any error to report? if(error) break; //Parse intermediate certificate error = x509ParseCertificate(p, n, issuerCertInfo); //Failed to parse the X.509 certificate? if(error) { //Report an error error = ERROR_BAD_CERTIFICATE; break; } //Certificate chain validation in progress? if(certValidResult == ERROR_UNKNOWN_CA) { //Validate current certificate error = x509ValidateCertificate(certInfo, issuerCertInfo, i); //Certificate validation failed? if(error) break; //Check name constraints error = x509CheckNameConstraints(subjectName, issuerCertInfo); //Should the application reject the certificate? if(error) return ERROR_BAD_CERTIFICATE; //Check the version of the certificate if(issuerCertInfo->tbsCert.version < X509_VERSION_3) { //Conforming implementations may choose to reject all version 1 //and version 2 intermediate certificates (refer to RFC 5280, //section 6.1.4) error = ERROR_BAD_CERTIFICATE; break; } //Check if the intermediate certificate can be matched with a //trusted CA certValidResult = tlsValidateCertificate(context, issuerCertInfo, i, subjectName); //Check validation result if(certValidResult != NO_ERROR && certValidResult != ERROR_UNKNOWN_CA) { //The certificate is not valid error = certValidResult; break; } } //Keep track of the issuer certificate *certInfo = *issuerCertInfo; //Next certificate p += n; length -= n; #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3) //TLS 1.3 currently selected? if(context->version == TLS_VERSION_1_3) { //Parse the list of extensions for the current CertificateEntry error = tls13ParseCertExtensions(p, length, &n); //Any error to report? if(error) break; //Point to the next field p += n; //Remaining bytes to process length -= n; } #endif } //Certificate chain validation failed? if(error == NO_ERROR && certValidResult != NO_ERROR) { //A valid certificate chain or partial chain was received, but the //certificate was not accepted because the CA certificate could not //be matched with a known, trusted CA error = ERROR_UNKNOWN_CA; } //End of exception handling block } while(0); //Free previously allocated memory tlsFreeMem(certInfo); tlsFreeMem(issuerCertInfo); //Return status code return error; }
/** * @brief Parse certificate chain * @param[in] context Pointer to the TLS context * @param[in] p Input stream where to read the certificate chain * @param[in] length Number of bytes available in the input stream * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_ssl/tls_certificate.c#L285-L585
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tlsParseRawPublicKey
error_t tlsParseRawPublicKey(TlsContext *context, const uint8_t *p, size_t length) { error_t error; #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED) //Any registered callback? if(context->rpkVerifyCallback != NULL) { size_t n; size_t rawPublicKeyLen; const uint8_t *rawPublicKey; X509SubjectPublicKeyInfo subjectPublicKeyInfo; #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3) //TLS 1.3 currently selected? if(context->version == TLS_VERSION_1_3) { //The raw public key is preceded by a 3-byte length field if(length < 3) return ERROR_DECODING_FAILED; //Get the size occupied by the raw public key rawPublicKeyLen = LOAD24BE(p); //Advance data pointer p += 3; //Remaining bytes to process length -= 3; //Malformed Certificate message? if(length < rawPublicKeyLen) return ERROR_DECODING_FAILED; } else #endif { //The payload of the Certificate message contains a SubjectPublicKeyInfo //structure rawPublicKeyLen = length; } //Point to the raw public key rawPublicKey = p; //Decode the SubjectPublicKeyInfo structure error = x509ParseSubjectPublicKeyInfo(rawPublicKey, rawPublicKeyLen, &n, &subjectPublicKeyInfo); //Any error to report? if(error) return error; //Advance data pointer p += rawPublicKeyLen; //Remaining bytes to process length -= rawPublicKeyLen; #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3) //TLS 1.3 currently selected? if(context->version == TLS_VERSION_1_3) { //Parse the list of extensions for the current CertificateEntry error = tls13ParseCertExtensions(p, length, &n); //Any error to report? if(error) return error; //Advance data pointer p += n; //Remaining bytes to process length -= n; } #endif //If the RawPublicKey certificate type was negotiated, the certificate //list must contain no more than one CertificateEntry (refer to RFC 8446, //section 4.4.2) if(length != 0) return ERROR_DECODING_FAILED; //Extract the public key from the SubjectPublicKeyInfo structure error = tlsReadSubjectPublicKey(context, &subjectPublicKeyInfo); //Any error to report? if(error) return error; //When raw public keys are used, authentication of the peer is supported //only through authentication of the received SubjectPublicKeyInfo via an //out-of-band method error = context->rpkVerifyCallback(context, rawPublicKey, rawPublicKeyLen); } else #endif { //Report an error error = ERROR_BAD_CERTIFICATE; } //Return status code return error; }
/** * @brief Parse raw public key * @param[in] context Pointer to the TLS context * @param[in] p Input stream where to read the raw public key * @param[in] length Number of bytes available in the input stream * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_ssl/tls_certificate.c#L596-L696
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tlsIsCertificateAcceptable
bool_t tlsIsCertificateAcceptable(TlsContext *context, const TlsCertDesc *cert, const uint8_t *certTypes, size_t numCertTypes, const TlsSignHashAlgos *signHashAlgos, const TlsSignHashAlgos *certSignHashAlgos, const TlsSupportedGroupList *curveList, const TlsCertAuthorities *certAuthorities) { size_t i; size_t n; size_t length; bool_t acceptable; //Make sure that a valid certificate has been loaded if(cert->certChain == NULL || cert->certChainLen == 0) return FALSE; #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED) //RSA certificate? if(cert->type == TLS_CERT_RSA_SIGN) { //This flag tells whether the certificate is acceptable acceptable = TRUE; //Version of TLS prior to TLS 1.2? if(context->version <= TLS_VERSION_1_1) { //the signing algorithm for the certificate must be the same as the //algorithm for the certificate key if(cert->signAlgo != TLS_SIGN_ALGO_RSA) acceptable = FALSE; } //Filter out certificates with unsupported type if(acceptable && certTypes != NULL) { //Loop through the list of supported certificate types for(i = 0, acceptable = FALSE; i < numCertTypes && !acceptable; i++) { //Check whether the certificate type is acceptable if(certTypes[i] == TLS_CERT_RSA_SIGN) { acceptable = TRUE; } } } //Filter out certificates that are not compatible with the supported //signature schemes if(acceptable && signHashAlgos != NULL) { //Retrieve the number of items in the list n = ntohs(signHashAlgos->length) / sizeof(TlsSignHashAlgo); //Loop through the list of supported hash/signature algorithm pairs for(i = 0, acceptable = FALSE; i < n && !acceptable; i++) { uint8_t signAlgo; uint8_t hashAlgo; //Retrieve signature and hash algorithms signAlgo = signHashAlgos->value[i].signature; hashAlgo = signHashAlgos->value[i].hash; #if (TLS_RSA_SIGN_SUPPORT == ENABLED) //RSASSA-PKCS1-v1_5 signature scheme? if(signAlgo == TLS_SIGN_ALGO_RSA && hashAlgo != TLS_HASH_ALGO_NONE && context->version <= TLS_VERSION_1_2) { acceptable = TRUE; } else #endif #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED && TLS_SHA256_SUPPORT == ENABLED) //RSASSA-PSS RSAE signature scheme with SHA-256? if(signAlgo == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA256 && hashAlgo == TLS_HASH_ALGO_INTRINSIC && context->version >= TLS_VERSION_1_2) { acceptable = TRUE; } else #endif #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED && TLS_SHA384_SUPPORT == ENABLED) //RSASSA-PSS RSAE signature scheme with SHA-384? if(signAlgo == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA384 && hashAlgo == TLS_HASH_ALGO_INTRINSIC && context->version >= TLS_VERSION_1_2) { acceptable = TRUE; } else #endif #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED && TLS_SHA512_SUPPORT == ENABLED) //RSASSA-PSS RSAE signature scheme with SHA-512? if(signAlgo == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA512 && hashAlgo == TLS_HASH_ALGO_INTRINSIC && context->version >= TLS_VERSION_1_2) { acceptable = TRUE; } else #endif //Unknown signature scheme? { acceptable = FALSE; } } } } else #endif #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED) //RSA-PSS certificate? if(cert->type == TLS_CERT_RSA_PSS_SIGN) { //TLS 1.2 and TLS 1.3 support RSASSA-PSS signature schemes if(context->version >= TLS_VERSION_1_2) { //Filter out certificates that are not compatible with the supported //signature schemes if(signHashAlgos != NULL) { //Retrieve the number of items in the list n = ntohs(signHashAlgos->length) / sizeof(TlsSignHashAlgo); //Loop through the list of supported hash/signature algorithm pairs for(i = 0, acceptable = FALSE; i < n && !acceptable; i++) { uint8_t signAlgo; uint8_t hashAlgo; //Retrieve signature and hash algorithms signAlgo = signHashAlgos->value[i].signature; hashAlgo = signHashAlgos->value[i].hash; #if (TLS_SHA256_SUPPORT == ENABLED) //RSASSA-PSS PSS signature scheme with SHA-256? if(signAlgo == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA256 && hashAlgo == TLS_HASH_ALGO_INTRINSIC) { acceptable = TRUE; } else #endif #if (TLS_SHA384_SUPPORT == ENABLED) //RSASSA-PSS PSS signature scheme with SHA-384? if(signAlgo == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA384 && hashAlgo == TLS_HASH_ALGO_INTRINSIC) { acceptable = TRUE; } else #endif #if (TLS_SHA512_SUPPORT == ENABLED) //RSASSA-PSS PSS signature scheme with SHA-512? if(signAlgo == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA512 && hashAlgo == TLS_HASH_ALGO_INTRINSIC) { acceptable = TRUE; } else #endif //Unknown signature scheme? { acceptable = FALSE; } } } else { //The SignatureAlgorithms extension must be specified (refer to //RFC 8446, section 4.3.2) acceptable = FALSE; } } else { //RSA-PSS is not supported by TLS 1.2 and earlier acceptable = FALSE; } } else #endif #if (TLS_DSA_SIGN_SUPPORT == ENABLED) //DSA certificate? if(cert->type == TLS_CERT_DSS_SIGN) { //Version of TLS prior to TLS 1.3? if(context->version <= TLS_VERSION_1_2) { //This flag tells whether the certificate is acceptable acceptable = TRUE; //Version of TLS prior to TLS 1.2? if(context->version <= TLS_VERSION_1_1) { //the signing algorithm for the certificate must be the same as the //algorithm for the certificate key if(cert->signAlgo != TLS_SIGN_ALGO_DSA) acceptable = FALSE; } //Filter out certificates with unsupported type if(acceptable && certTypes != NULL) { //Loop through the list of supported certificate types for(i = 0, acceptable = FALSE; i < numCertTypes && !acceptable; i++) { //Check whether the certificate type is acceptable if(certTypes[i] == TLS_CERT_DSS_SIGN) { acceptable = TRUE; } } } //Filter out certificates that are not compatible with the supported //signature schemes if(acceptable && signHashAlgos != NULL) { //Retrieve the number of items in the list n = ntohs(signHashAlgos->length) / sizeof(TlsSignHashAlgo); //Loop through the list of supported hash/signature algorithm pairs for(i = 0, acceptable = FALSE; i < n && !acceptable; i++) { //Check whether DSA signature scheme is supported if(signHashAlgos->value[i].signature == TLS_SIGN_ALGO_DSA) { acceptable = TRUE; } } } } else { //TLS 1.3 removes support for DSA certificates acceptable = FALSE; } } else #endif #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED) //ECDSA certificate? if(cert->type == TLS_CERT_ECDSA_SIGN) { //This flag tells whether the certificate is acceptable acceptable = TRUE; //Version of TLS prior to TLS 1.2? if(context->version <= TLS_VERSION_1_1) { //the signing algorithm for the certificate must be the same as the //algorithm for the certificate key if(cert->signAlgo != TLS_SIGN_ALGO_ECDSA) { acceptable = FALSE; } } //Filter out certificates with unsupported type if(acceptable && certTypes != NULL) { //Loop through the list of supported certificate types for(i = 0, acceptable = FALSE; i < numCertTypes && !acceptable; i++) { //Check whether the certificate type is acceptable if(certTypes[i] == TLS_CERT_ECDSA_SIGN) { acceptable = TRUE; } } } //Version of TLS prior to TLS 1.3? if(context->version <= TLS_VERSION_1_2) { //In versions of TLS prior to TLS 1.3, the EllipticCurves extension is //used to negotiate ECDSA curves (refer to RFC 8446, section 4.2.7) if(acceptable && curveList != NULL) { //Retrieve the number of items in the list n = ntohs(curveList->length) / sizeof(uint16_t); //Loop through the list of supported elliptic curves for(i = 0, acceptable = FALSE; i < n && !acceptable; i++) { //Check whether the elliptic curve is supported if(ntohs(curveList->value[i]) == cert->namedCurve) { acceptable = TRUE; } } } } //Filter out certificates that are not compatible with the supported //signature schemes if(acceptable && signHashAlgos != NULL) { //Retrieve the number of items in the list n = ntohs(signHashAlgos->length) / sizeof(TlsSignHashAlgo); //Loop through the list of supported hash/signature algorithm pairs for(i = 0, acceptable = FALSE; i < n && !acceptable; i++) { //Check whether ECDSA signature scheme is supported if(signHashAlgos->value[i].signature == TLS_SIGN_ALGO_ECDSA) { acceptable = TRUE; } } } } else #endif #if (TLS_EDDSA_SIGN_SUPPORT == ENABLED) //EdDSA certificate? if(cert->type == TLS_CERT_ED25519_SIGN || cert->type == TLS_CERT_ED448_SIGN) { //TLS 1.2 and TLS 1.3 support EdDSA signature schemes if((context->version >= TLS_VERSION_1_2 && context->entity == TLS_CONNECTION_END_SERVER) || (context->version >= TLS_VERSION_1_3 && context->entity == TLS_CONNECTION_END_CLIENT)) { //This flag tells whether the certificate is acceptable acceptable = TRUE; //Filter out certificates with unsupported type if(certTypes != NULL) { //Loop through the list of supported certificate types for(i = 0, acceptable = FALSE; i < numCertTypes && !acceptable; i++) { //Check whether the certificate type is acceptable if(certTypes[i] == TLS_CERT_ECDSA_SIGN) { acceptable = TRUE; } } } //Filter out certificates that are not compatible with the supported //signature schemes if(acceptable && signHashAlgos != NULL) { //Retrieve the number of items in the list n = ntohs(signHashAlgos->length) / sizeof(TlsSignHashAlgo); //Loop through the list of supported hash/signature algorithm pairs for(i = 0, acceptable = FALSE; i < n && !acceptable; i++) { #if (TLS_ED25519_SUPPORT == ENABLED) //Ed25519 certificate? if(cert->type == TLS_CERT_ED25519_SIGN) { //Check whether Ed25519 signature scheme is supported if(signHashAlgos->value[i].signature == TLS_SIGN_ALGO_ED25519 && signHashAlgos->value[i].hash == TLS_HASH_ALGO_INTRINSIC) { acceptable = TRUE; } } else #endif #if (TLS_ED448_SUPPORT == ENABLED) //Ed448 certificate? if(cert->type == TLS_CERT_ED448_SIGN) { //Check whether Ed448 signature scheme is supported if(signHashAlgos->value[i].signature == TLS_SIGN_ALGO_ED448 && signHashAlgos->value[i].hash == TLS_HASH_ALGO_INTRINSIC) { acceptable = TRUE; } } else #endif //Unknown certificate type? { acceptable = FALSE; } } } else { //The certificate is not acceptable acceptable = FALSE; } } else { //EdDSA is not supported by TLS 1.1 and earlier acceptable = FALSE; } } else #endif //Unsupported certificate type? { //The certificate is not acceptable acceptable = FALSE; } //Filter out certificates that are signed with an unsupported algorithm if(acceptable && certSignHashAlgos != NULL) { //Retrieve the number of items in the list n = ntohs(certSignHashAlgos->length) / sizeof(TlsSignHashAlgo); //Loop through the list of supported hash/signature algorithm pairs for(i = 0, acceptable = FALSE; i < n && !acceptable; i++) { //The certificate must be signed using a valid hash algorithm if(certSignHashAlgos->value[i].signature == cert->signAlgo && certSignHashAlgos->value[i].hash == cert->hashAlgo) { acceptable = TRUE; } } } //Filter out certificates that are issued by a non trusted CA if(acceptable && certAuthorities != NULL) { //Retrieve the length of the list length = ntohs(certAuthorities->length); //If the certificate authorities list is empty, then the client //may send any certificate of the appropriate type if(length > 0) { error_t error; size_t pemCertLen; const char_t *certChain; size_t certChainLen; uint8_t *derCert; size_t derCertLen; X509CertInfo *certInfo; //The list of acceptable certificate authorities describes the //known roots CA acceptable = FALSE; //Point to the end entity certificate certChain = cert->certChain; //Get the total length, in bytes, of the certificate chain certChainLen = cert->certChainLen; //Allocate a memory buffer to store X.509 certificate info certInfo = tlsAllocMem(sizeof(X509CertInfo)); //Successful memory allocation? if(certInfo != NULL) { //Parse the certificate chain while(certChainLen > 0 && !acceptable) { //The first pass calculates the length of the DER-encoded //certificate error = pemImportCertificate(certChain, certChainLen, NULL, &derCertLen, &pemCertLen); //Check status code if(!error) { //Allocate a memory buffer to hold the DER-encoded certificate derCert = tlsAllocMem(derCertLen); //Successful memory allocation? if(derCert != NULL) { //The second pass decodes the PEM certificate error = pemImportCertificate(certChain, certChainLen, derCert, &derCertLen, NULL); //Check status code if(!error) { //Parse X.509 certificate error = x509ParseCertificate(derCert, derCertLen, certInfo); } //Check status code if(!error) { //Parse each distinguished name of the list for(i = 0; i < length; i += n + 2) { //Sanity check if((i + 2) > length) break; //Each distinguished name is preceded by a 2-byte //length field n = LOAD16BE(certAuthorities->value + i); //Make sure the length field is valid if((i + n + 2) > length) break; //Check if the distinguished name matches the root CA if(x509CompareName(certAuthorities->value + i + 2, n, certInfo->tbsCert.issuer.raw.value, certInfo->tbsCert.issuer.raw.length)) { acceptable = TRUE; break; } } } //Free previously allocated memory tlsFreeMem(derCert); } //Advance read pointer certChain += pemCertLen; certChainLen -= pemCertLen; } else { //No more CA certificates in the list break; } } //Free previously allocated memory tlsFreeMem(certInfo); } } } //The return value specifies whether all the criteria were matched return acceptable; }
/** * @brief Check whether a certificate is acceptable * @param[in] context Pointer to the TLS context * @param[in] cert End entity certificate * @param[in] certTypes List of supported certificate types * @param[in] numCertTypes Size of the list that contains the supported * certificate types * @param[in] signHashAlgos List of signature algorithms that may be used in * digital signatures * @param[in] certSignHashAlgos List of signature algorithms that may be used * in X.509 certificates * @param[in] curveList List of supported elliptic curves * @param[in] certAuthorities List of trusted CA * @return TRUE if the specified certificate conforms to the requirements, * else FALSE **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_ssl/tls_certificate.c#L716-L1253
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tlsValidateCertificate
error_t tlsValidateCertificate(TlsContext *context, const X509CertInfo *certInfo, uint_t pathLen, const char_t *subjectName) { error_t error; size_t pemCertLen; const char_t *trustedCaList; size_t trustedCaListLen; uint8_t *derCert; size_t derCertLen; X509CertInfo *caCertInfo; //Initialize status code error = ERROR_UNKNOWN_CA; //Any registered callback? if(context->certVerifyCallback != NULL) { //Invoke user callback function error = context->certVerifyCallback(context, certInfo, pathLen, context->certVerifyParam); } //Check status code if(error == NO_ERROR) { //The certificate is valid } else if(error == ERROR_UNKNOWN_CA) { //Check whether the certificate should be checked against root CAs if(context->trustedCaListLen > 0) { //Point to the first trusted CA certificate trustedCaList = context->trustedCaList; //Get the total length, in bytes, of the trusted CA list trustedCaListLen = context->trustedCaListLen; //Allocate a memory buffer to store X.509 certificate info caCertInfo = tlsAllocMem(sizeof(X509CertInfo)); //Successful memory allocation? if(caCertInfo != NULL) { //Loop through the list of trusted CA certificates while(trustedCaListLen > 0 && error == ERROR_UNKNOWN_CA) { //The first pass calculates the length of the DER-encoded //certificate error = pemImportCertificate(trustedCaList, trustedCaListLen, NULL, &derCertLen, &pemCertLen); //Check status code if(!error) { //Allocate a memory buffer to hold the DER-encoded certificate derCert = tlsAllocMem(derCertLen); //Successful memory allocation? if(derCert != NULL) { //The second pass decodes the PEM certificate error = pemImportCertificate(trustedCaList, trustedCaListLen, derCert, &derCertLen, NULL); //Check status code if(!error) { //Parse X.509 certificate error = x509ParseCertificate(derCert, derCertLen, caCertInfo); } //Check status code if(!error) { //Validate the certificate with the current CA error = x509ValidateCertificate(certInfo, caCertInfo, pathLen); } //Check status code if(!error) { //Check name constraints error = x509CheckNameConstraints(subjectName, caCertInfo); } //Check status code if(!error) { //The certificate is issued by a trusted CA error = NO_ERROR; } else { //The certificate cannot be matched with the current CA error = ERROR_UNKNOWN_CA; } //Free previously allocated memory tlsFreeMem(derCert); } else { //Failed to allocate memory error = ERROR_OUT_OF_MEMORY; } //Advance read pointer trustedCaList += pemCertLen; trustedCaListLen -= pemCertLen; } else { //No more CA certificates in the list trustedCaListLen = 0; error = ERROR_UNKNOWN_CA; } } //Free previously allocated memory tlsFreeMem(caCertInfo); } else { //Failed to allocate memory error = ERROR_OUT_OF_MEMORY; } } else { //Do not check the certificate against root CAs error = NO_ERROR; } } else if(error == ERROR_BAD_CERTIFICATE || error == ERROR_UNSUPPORTED_CERTIFICATE || error == ERROR_UNKNOWN_CERTIFICATE || error == ERROR_CERTIFICATE_REVOKED || error == ERROR_CERTIFICATE_EXPIRED || error == ERROR_HANDSHAKE_FAILED) { //The certificate is not valid } else { //Report an error error = ERROR_BAD_CERTIFICATE; } //Return status code return error; }
/** * @brief Verify certificate against root CAs * @param[in] context Pointer to the TLS context * @param[in] certInfo X.509 certificate to be verified * @param[in] pathLen Certificate path length * @param[in] subjectName Subject name (optional parameter) * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_ssl/tls_certificate.c#L1265-L1418
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tlsGetCertificateType
error_t tlsGetCertificateType(const X509CertInfo *certInfo, TlsCertificateType *certType, TlsNamedGroup *namedCurve) { size_t oidLen; const uint8_t *oid; //Check parameters if(certInfo == NULL || certType == NULL || namedCurve == NULL) return ERROR_INVALID_PARAMETER; //Point to the public key identifier oid = certInfo->tbsCert.subjectPublicKeyInfo.oid.value; oidLen = certInfo->tbsCert.subjectPublicKeyInfo.oid.length; #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED) //RSA public key? if(!oidComp(oid, oidLen, RSA_ENCRYPTION_OID, sizeof(RSA_ENCRYPTION_OID))) { //Save certificate type *certType = TLS_CERT_RSA_SIGN; //No named curve applicable *namedCurve = TLS_GROUP_NONE; } else #endif #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED) //RSA-PSS public key? if(!oidComp(oid, oidLen, RSASSA_PSS_OID, sizeof(RSASSA_PSS_OID))) { //Save certificate type *certType = TLS_CERT_RSA_PSS_SIGN; //No named curve applicable *namedCurve = TLS_GROUP_NONE; } else #endif #if (TLS_DSA_SIGN_SUPPORT == ENABLED) //DSA public key? if(!oidComp(oid, oidLen, DSA_OID, sizeof(DSA_OID))) { //Save certificate type *certType = TLS_CERT_DSS_SIGN; //No named curve applicable *namedCurve = TLS_GROUP_NONE; } else #endif #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED) //EC public key? if(!oidComp(oid, oidLen, EC_PUBLIC_KEY_OID, sizeof(EC_PUBLIC_KEY_OID))) { const X509EcParameters *params; //Point to the EC parameters params = &certInfo->tbsCert.subjectPublicKeyInfo.ecParams; //Save certificate type *certType = TLS_CERT_ECDSA_SIGN; //Retrieve the named curve that has been used to generate the EC //public key *namedCurve = tlsGetNamedCurve(params->namedCurve.value, params->namedCurve.length); } else #endif #if (TLS_EDDSA_SIGN_SUPPORT == ENABLED) //Ed25519 public key? if(!oidComp(oid, oidLen, ED25519_OID, sizeof(ED25519_OID))) { //Save certificate type *certType = TLS_CERT_ED25519_SIGN; //No named curve applicable *namedCurve = TLS_GROUP_NONE; } else //Ed448 public key? if(!oidComp(oid, oidLen, ED448_OID, sizeof(ED448_OID))) { //Save certificate type *certType = TLS_CERT_ED448_SIGN; //No named curve applicable *namedCurve = TLS_GROUP_NONE; } else #endif //Invalid public key? { //The certificate does not contain any valid public key return ERROR_BAD_CERTIFICATE; } //Successful processing return NO_ERROR; }
/** * @brief Retrieve the certificate type * @param[in] certInfo X.509 certificate * @param[out] certType Certificate type * @param[out] namedCurve Elliptic curve (only for ECDSA certificates) * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_ssl/tls_certificate.c#L1429-L1523
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tlsGetCertificateSignAlgo
error_t tlsGetCertificateSignAlgo(const X509CertInfo *certInfo, TlsSignatureAlgo *signAlgo, TlsHashAlgo *hashAlgo) { size_t oidLen; const uint8_t *oid; //Check parameters if(certInfo == NULL || signAlgo == NULL || hashAlgo == NULL) return ERROR_INVALID_PARAMETER; //Point to the signature algorithm oid = certInfo->signatureAlgo.oid.value; oidLen = certInfo->signatureAlgo.oid.length; #if (RSA_SUPPORT == ENABLED) //RSA signature algorithm? if(!oidComp(oid, oidLen, MD5_WITH_RSA_ENCRYPTION_OID, sizeof(MD5_WITH_RSA_ENCRYPTION_OID))) { //MD5 with RSA signature algorithm *signAlgo = TLS_SIGN_ALGO_RSA; *hashAlgo = TLS_HASH_ALGO_MD5; } else if(!oidComp(oid, oidLen, SHA1_WITH_RSA_ENCRYPTION_OID, sizeof(SHA1_WITH_RSA_ENCRYPTION_OID))) { //SHA-1 with RSA signature algorithm *signAlgo = TLS_SIGN_ALGO_RSA; *hashAlgo = TLS_HASH_ALGO_SHA1; } else if(!oidComp(oid, oidLen, SHA256_WITH_RSA_ENCRYPTION_OID, sizeof(SHA256_WITH_RSA_ENCRYPTION_OID))) { //SHA-256 with RSA signature algorithm *signAlgo = TLS_SIGN_ALGO_RSA; *hashAlgo = TLS_HASH_ALGO_SHA256; } else if(!oidComp(oid, oidLen, SHA384_WITH_RSA_ENCRYPTION_OID, sizeof(SHA384_WITH_RSA_ENCRYPTION_OID))) { //SHA-384 with RSA signature algorithm *signAlgo = TLS_SIGN_ALGO_RSA; *hashAlgo = TLS_HASH_ALGO_SHA384; } else if(!oidComp(oid, oidLen, SHA512_WITH_RSA_ENCRYPTION_OID, sizeof(SHA512_WITH_RSA_ENCRYPTION_OID))) { //SHA-512 with RSA signature algorithm *signAlgo = TLS_SIGN_ALGO_RSA; *hashAlgo = TLS_HASH_ALGO_SHA512; } else #endif #if (RSA_SUPPORT == ENABLED && X509_RSA_PSS_SUPPORT == ENABLED) //RSA-PSS signature algorithm? if(!oidComp(oid, oidLen, RSASSA_PSS_OID, sizeof(RSASSA_PSS_OID))) { //Get the OID of the hash algorithm oid = certInfo->signatureAlgo.rsaPssParams.hashAlgo.value; oidLen = certInfo->signatureAlgo.rsaPssParams.hashAlgo.length; #if (SHA256_SUPPORT == ENABLED) //SHA-256 hash algorithm identifier? if(!oidComp(oid, oidLen, SHA256_OID, sizeof(SHA256_OID))) { //RSA-PSS with SHA-256 signature algorithm *signAlgo = TLS_SIGN_ALGO_RSA_PSS_PSS_SHA256; *hashAlgo = TLS_HASH_ALGO_INTRINSIC; } else #endif #if (SHA384_SUPPORT == ENABLED) //SHA-384 hash algorithm identifier? if(!oidComp(oid, oidLen, SHA384_OID, sizeof(SHA384_OID))) { //RSA-PSS with SHA-384 signature algorithm *signAlgo = TLS_SIGN_ALGO_RSA_PSS_PSS_SHA384; *hashAlgo = TLS_HASH_ALGO_INTRINSIC; } else #endif #if (SHA512_SUPPORT == ENABLED) //SHA-512 hash algorithm identifier? if(!oidComp(oid, oidLen, SHA512_OID, sizeof(SHA512_OID))) { //RSA-PSS with SHA-512 signature algorithm *signAlgo = TLS_SIGN_ALGO_RSA_PSS_PSS_SHA512; *hashAlgo = TLS_HASH_ALGO_INTRINSIC; } else #endif //Unknown hash algorithm identifier? { //The signature algorithm is not supported return ERROR_BAD_CERTIFICATE; } } else #endif #if (DSA_SUPPORT == ENABLED) //DSA signature algorithm? if(!oidComp(oid, oidLen, DSA_WITH_SHA1_OID, sizeof(DSA_WITH_SHA1_OID))) { //DSA with SHA-1 signature algorithm *signAlgo = TLS_SIGN_ALGO_DSA; *hashAlgo = TLS_HASH_ALGO_SHA1; } else if(!oidComp(oid, oidLen, DSA_WITH_SHA224_OID, sizeof(DSA_WITH_SHA224_OID))) { //DSA with SHA-224 signature algorithm *signAlgo = TLS_SIGN_ALGO_DSA; *hashAlgo = TLS_HASH_ALGO_SHA224; } else if(!oidComp(oid, oidLen, DSA_WITH_SHA256_OID, sizeof(DSA_WITH_SHA256_OID))) { //DSA with SHA-256 signature algorithm *signAlgo = TLS_SIGN_ALGO_DSA; *hashAlgo = TLS_HASH_ALGO_SHA256; } else #endif #if (ECDSA_SUPPORT == ENABLED) //ECDSA signature algorithm? if(!oidComp(oid, oidLen, ECDSA_WITH_SHA1_OID, sizeof(ECDSA_WITH_SHA1_OID))) { //ECDSA with SHA-1 signature algorithm *signAlgo = TLS_SIGN_ALGO_ECDSA; *hashAlgo = TLS_HASH_ALGO_SHA1; } else if(!oidComp(oid, oidLen, ECDSA_WITH_SHA224_OID, sizeof(ECDSA_WITH_SHA224_OID))) { //ECDSA with SHA-224 signature algorithm *signAlgo = TLS_SIGN_ALGO_ECDSA; *hashAlgo = TLS_HASH_ALGO_SHA224; } else if(!oidComp(oid, oidLen, ECDSA_WITH_SHA256_OID, sizeof(ECDSA_WITH_SHA256_OID))) { //ECDSA with SHA-256 signature algorithm *signAlgo = TLS_SIGN_ALGO_ECDSA; *hashAlgo = TLS_HASH_ALGO_SHA256; } else if(!oidComp(oid, oidLen, ECDSA_WITH_SHA384_OID, sizeof(ECDSA_WITH_SHA384_OID))) { //ECDSA with SHA-384 signature algorithm *signAlgo = TLS_SIGN_ALGO_ECDSA; *hashAlgo = TLS_HASH_ALGO_SHA384; } else if(!oidComp(oid, oidLen, ECDSA_WITH_SHA512_OID, sizeof(ECDSA_WITH_SHA512_OID))) { //ECDSA with SHA-512 signature algorithm *signAlgo = TLS_SIGN_ALGO_ECDSA; *hashAlgo = TLS_HASH_ALGO_SHA512; } else #endif #if (ED25519_SUPPORT == ENABLED) //Ed25519 signature algorithm? if(!oidComp(oid, oidLen, ED25519_OID, sizeof(ED25519_OID))) { //Ed25519 signature algorithm *signAlgo = TLS_SIGN_ALGO_ED25519; *hashAlgo = TLS_HASH_ALGO_INTRINSIC; } else #endif #if (ED448_SUPPORT == ENABLED) //Ed448 signature algorithm? if(!oidComp(oid, oidLen, ED448_OID, sizeof(ED448_OID))) { //Ed448 signature algorithm *signAlgo = TLS_SIGN_ALGO_ED448; *hashAlgo = TLS_HASH_ALGO_INTRINSIC; } else #endif //Unknown signature algorithm? { //The signature algorithm is not supported return ERROR_BAD_CERTIFICATE; } //Successful processing return NO_ERROR; }
/** * @brief Retrieve the signature algorithm used to sign the certificate * @param[in] certInfo X.509 certificate * @param[out] signAlgo Signature algorithm * @param[out] hashAlgo Hash algorithm * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_ssl/tls_certificate.c#L1534-L1725
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tlsReadSubjectPublicKey
error_t tlsReadSubjectPublicKey(TlsContext *context, const X509SubjectPublicKeyInfo *subjectPublicKeyInfo) { error_t error; size_t oidLen; const uint8_t *oid; //Retrieve public key identifier oid = subjectPublicKeyInfo->oid.value; oidLen = subjectPublicKeyInfo->oid.length; #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED) //RSA public key? if(!oidComp(oid, oidLen, RSA_ENCRYPTION_OID, sizeof(RSA_ENCRYPTION_OID)) || !oidComp(oid, oidLen, RSASSA_PSS_OID, sizeof(RSASSA_PSS_OID))) { uint_t k; //Import the RSA public key error = x509ImportRsaPublicKey(subjectPublicKeyInfo, &context->peerRsaPublicKey); //Check status code if(!error) { //Get the length of the modulus, in bits k = mpiGetBitLength(&context->peerRsaPublicKey.n); //Applications should also enforce minimum and maximum key sizes (refer //to RFC 8446, appendix C.2) if(k < TLS_MIN_RSA_MODULUS_SIZE || k > TLS_MAX_RSA_MODULUS_SIZE) { //Report an error error = ERROR_BAD_CERTIFICATE; } } //Check status code if(!error) { //RSA or RSA-PSS certificate? if(!oidComp(oid, oidLen, RSA_ENCRYPTION_OID, sizeof(RSA_ENCRYPTION_OID))) { //The certificate contains a valid RSA public key context->peerCertType = TLS_CERT_RSA_SIGN; } else if(!oidComp(oid, oidLen, RSASSA_PSS_OID, sizeof(RSASSA_PSS_OID))) { //The certificate contains a valid RSA-PSS public key context->peerCertType = TLS_CERT_RSA_PSS_SIGN; } else { //Just for sanity error = ERROR_BAD_CERTIFICATE; } } } else #endif #if (TLS_DSA_SIGN_SUPPORT == ENABLED) //DSA public key? if(!oidComp(oid, oidLen, DSA_OID, sizeof(DSA_OID))) { uint_t k; //Import the DSA public key error = x509ImportDsaPublicKey(subjectPublicKeyInfo, &context->peerDsaPublicKey); //Check status code if(!error) { //Get the length of the prime modulus, in bits k = mpiGetBitLength(&context->peerDsaPublicKey.params.p); //Make sure the prime modulus is acceptable if(k < TLS_MIN_DSA_MODULUS_SIZE || k > TLS_MAX_DSA_MODULUS_SIZE) { //Report an error error = ERROR_BAD_CERTIFICATE; } } //Check status code if(!error) { //The certificate contains a valid DSA public key context->peerCertType = TLS_CERT_DSS_SIGN; } } else #endif #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED) //EC public key? if(!oidComp(oid, oidLen, EC_PUBLIC_KEY_OID, sizeof(EC_PUBLIC_KEY_OID))) { const EcCurveInfo *curveInfo; //Retrieve EC domain parameters curveInfo = x509GetCurveInfo(subjectPublicKeyInfo->ecParams.namedCurve.value, subjectPublicKeyInfo->ecParams.namedCurve.length); //Make sure the specified elliptic curve is supported if(curveInfo != NULL) { //Load EC domain parameters error = ecLoadDomainParameters(&context->peerEcParams, curveInfo); //Check status code if(!error) { //Retrieve the EC public key error = ecImport(&context->peerEcParams, &context->peerEcPublicKey.q, subjectPublicKeyInfo->ecPublicKey.q.value, subjectPublicKeyInfo->ecPublicKey.q.length); } } else { //The specified elliptic curve is not supported error = ERROR_BAD_CERTIFICATE; } //Check status code if(!error) { //The certificate contains a valid EC public key context->peerCertType = TLS_CERT_ECDSA_SIGN; } } else #endif #if (TLS_EDDSA_SIGN_SUPPORT == ENABLED) //Ed25519 or Ed448 public key? if(!oidComp(oid, oidLen, ED25519_OID, sizeof(ED25519_OID)) || !oidComp(oid, oidLen, ED448_OID, sizeof(ED448_OID))) { const EcCurveInfo *curveInfo; //Retrieve EC domain parameters curveInfo = x509GetCurveInfo(oid, oidLen); //Make sure the specified elliptic curve is supported if(curveInfo != NULL) { //Load EC domain parameters error = ecLoadDomainParameters(&context->peerEcParams, curveInfo); //Check status code if(!error) { //Retrieve the EC public key error = ecImport(&context->peerEcParams, &context->peerEcPublicKey.q, subjectPublicKeyInfo->ecPublicKey.q.value, subjectPublicKeyInfo->ecPublicKey.q.length); } } else { //The specified elliptic curve is not supported error = ERROR_BAD_CERTIFICATE; } //Check status code if(!error) { //Ed25519 or Ed448 certificate? if(!oidComp(oid, oidLen, ED25519_OID, sizeof(ED25519_OID))) { //The certificate contains a valid Ed25519 public key context->peerCertType = TLS_CERT_ED25519_SIGN; } else if(!oidComp(oid, oidLen, ED448_OID, sizeof(ED448_OID))) { //The certificate contains a valid Ed448 public key context->peerCertType = TLS_CERT_ED448_SIGN; } else { //Just for sanity error = ERROR_BAD_CERTIFICATE; } } } else #endif //Invalid public key? { //The certificate does not contain any valid public key error = ERROR_UNSUPPORTED_CERTIFICATE; } #if (TLS_CLIENT_SUPPORT == ENABLED) //Check status code if(!error) { //Client mode? if(context->entity == TLS_CONNECTION_END_CLIENT) { //Check key exchange method if(context->keyExchMethod == TLS_KEY_EXCH_RSA || context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA || context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA || context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK) { //The client expects a valid RSA certificate whenever the agreed- //upon key exchange method uses RSA certificates for authentication if(context->peerCertType != TLS_CERT_RSA_SIGN && context->peerCertType != TLS_CERT_RSA_PSS_SIGN) { error = ERROR_UNSUPPORTED_CERTIFICATE; } } else if(context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS) { //The client expects a valid DSA certificate whenever the agreed- //upon key exchange method uses DSA certificates for authentication if(context->peerCertType != TLS_CERT_DSS_SIGN) { error = ERROR_UNSUPPORTED_CERTIFICATE; } } else if(context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA) { //The client expects a valid ECDSA certificate whenever the agreed- //upon key exchange method uses ECDSA certificates for authentication if(context->peerCertType != TLS_CERT_ECDSA_SIGN && context->peerCertType != TLS_CERT_ED25519_SIGN && context->peerCertType != TLS_CERT_ED448_SIGN) { error = ERROR_UNSUPPORTED_CERTIFICATE; } } else if(context->keyExchMethod == TLS13_KEY_EXCH_DHE || context->keyExchMethod == TLS13_KEY_EXCH_ECDHE) { //TLS 1.3 removes support for DSA certificates if(context->peerCertType != TLS_CERT_RSA_SIGN && context->peerCertType != TLS_CERT_RSA_PSS_SIGN && context->peerCertType != TLS_CERT_ECDSA_SIGN && context->peerCertType != TLS_CERT_ED25519_SIGN && context->peerCertType != TLS_CERT_ED448_SIGN) { error = ERROR_UNSUPPORTED_CERTIFICATE; } } else { //Just for sanity error = ERROR_UNSUPPORTED_CERTIFICATE; } } } #endif //Return status code return error; }
/** * @brief Extract the subject public key from the received certificate * @param[in] context Pointer to the TLS context * @param[in] subjectPublicKeyInfo Pointer to the subject's public key * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_ssl/tls_certificate.c#L1735-L1993
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
tlsCheckKeyUsage
error_t tlsCheckKeyUsage(const X509CertInfo *certInfo, TlsConnectionEnd entity, TlsKeyExchMethod keyExchMethod) { #if (TLS_CERT_KEY_USAGE_SUPPORT == ENABLED) error_t error; const X509KeyUsage *keyUsage; const X509ExtendedKeyUsage *extKeyUsage; //Initialize status code error = NO_ERROR; //Point to the KeyUsage extension keyUsage = &certInfo->tbsCert.extensions.keyUsage; //Check if the KeyUsage extension is present if(keyUsage->bitmap != 0) { //Check whether TLS operates as a client or a server if(entity == TLS_CONNECTION_END_CLIENT) { //Check key exchange method if(keyExchMethod == TLS_KEY_EXCH_RSA || keyExchMethod == TLS_KEY_EXCH_RSA_PSK) { //The keyEncipherment bit must be asserted when the subject public //key is used for enciphering private or secret keys if((keyUsage->bitmap & X509_KEY_USAGE_KEY_ENCIPHERMENT) == 0) { error = ERROR_BAD_CERTIFICATE; } } else if(keyExchMethod == TLS_KEY_EXCH_DHE_RSA || keyExchMethod == TLS_KEY_EXCH_DHE_DSS || keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA || keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA || keyExchMethod == TLS13_KEY_EXCH_DHE || keyExchMethod == TLS13_KEY_EXCH_ECDHE) { //The digitalSignature bit must be asserted when the subject public //key is used for verifying digital signatures, other than signatures //on certificates and CRLs if((keyUsage->bitmap & X509_KEY_USAGE_DIGITAL_SIGNATURE) == 0) { error = ERROR_BAD_CERTIFICATE; } } else { //Just for sanity } } else { //The digitalSignature bit must be asserted when the subject public //key is used for verifying digital signatures, other than signatures //on certificates and CRLs if((keyUsage->bitmap & X509_KEY_USAGE_DIGITAL_SIGNATURE) == 0) { error = ERROR_BAD_CERTIFICATE; } } } //Point to the ExtendedKeyUsage extension extKeyUsage = &certInfo->tbsCert.extensions.extKeyUsage; //Check if the ExtendedKeyUsage extension is present if(extKeyUsage->bitmap != 0) { //Check whether TLS operates as a client or a server if(entity == TLS_CONNECTION_END_CLIENT) { //Make sure the certificate can be used for server authentication if((extKeyUsage->bitmap & X509_EXT_KEY_USAGE_SERVER_AUTH) == 0) { error = ERROR_BAD_CERTIFICATE; } } else { //Make sure the certificate can be used for client authentication if((extKeyUsage->bitmap & X509_EXT_KEY_USAGE_CLIENT_AUTH) == 0) { error = ERROR_BAD_CERTIFICATE; } } } //Return status code return error; #else //Do not check key usage return NO_ERROR; #endif }
/** * @brief Check certificate key usage * @param[in] certInfo Pointer to the X.509 certificate * @param[in] entity Specifies whether this entity is considered a client or a server * @param[in] keyExchMethod TLS key exchange method * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_ssl/tls_certificate.c#L2004-L2098
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpClientOpenConnection
error_t httpClientOpenConnection(HttpClientContext *context) { error_t error; //Open a TCP socket context->socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP); //Failed to open socket? if(context->socket == NULL) return ERROR_OPEN_FAILED; //Associate the socket with the relevant interface error = socketBindToInterface(context->socket, context->interface); //Any error to report? if(error) return error; //Set timeout error = socketSetTimeout(context->socket, context->timeout); //Any error to report? if(error) return error; #if (HTTP_CLIENT_TLS_SUPPORT == ENABLED) //TLS-secured connection? if(context->tlsInitCallback != NULL) { //Allocate TLS context context->tlsContext = tlsInit(); //Failed to allocate TLS context? if(context->tlsContext == NULL) return ERROR_OPEN_FAILED; //Select client operation mode error = tlsSetConnectionEnd(context->tlsContext, TLS_CONNECTION_END_CLIENT); //Any error to report? if(error) return error; //Bind TLS to the relevant socket error = tlsSetSocket(context->tlsContext, context->socket); //Any error to report? if(error) return error; //Set TX and RX buffer size error = tlsSetBufferSize(context->tlsContext, HTTP_CLIENT_TLS_TX_BUFFER_SIZE, HTTP_CLIENT_TLS_RX_BUFFER_SIZE); //Any error to report? if(error) return error; //Restore TLS session error = tlsRestoreSessionState(context->tlsContext, &context->tlsSession); //Any error to report? if(error) return error; //Perform TLS related initialization error = context->tlsInitCallback(context, context->tlsContext); //Any error to report? if(error) return error; } #endif //Successful processing return NO_ERROR; }
/** * @brief Open network connection * @param[in] context Pointer to the HTTP client context * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_client_transport.c#L51-L118
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpClientEstablishConnection
error_t httpClientEstablishConnection(HttpClientContext *context, const IpAddr *serverIpAddr, uint16_t serverPort) { error_t error; //Establish TCP connection error = socketConnect(context->socket, serverIpAddr, serverPort); //Any error to report? if(error) return error; #if (HTTP_CLIENT_TLS_SUPPORT == ENABLED) //TLS-secured connection? if(context->tlsContext != NULL) { //Establish TLS connection error = tlsConnect(context->tlsContext); //Any error to report? if(error) return error; } #endif //Successful processing return NO_ERROR; }
/** * @brief Establish network connection * @param[in] context Pointer to the HTTP client context * @param[in] serverIpAddr IP address of the HTTP server to connect to * @param[in] serverPort TCP port number that will be used to establish the * connection * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_client_transport.c#L130-L155
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpClientShutdownConnection
error_t httpClientShutdownConnection(HttpClientContext *context) { error_t error; //Initialize status code error = NO_ERROR; pcaplog_ctx_t ctx; ctx.local_endpoint.ipv4 = 0; ctx.local_endpoint.port = context->socket->localPort; ctx.remote_endpoint.ipv4 = context->socket->remoteIpAddr.ipv4Addr; ctx.remote_endpoint.port = context->socket->remotePort; ctx.pcap_data = &context->private.pcap_data; pcaplog_reset(&ctx); #if (HTTP_CLIENT_TLS_SUPPORT == ENABLED) //Valid TLS context? if(context->tlsContext != NULL) { //Shutdown TLS session error = tlsShutdown(context->tlsContext); } #endif //Check status code if(!error) { //Valid TCP socket? if(context->socket != NULL) { //Shutdown TCP connection error = socketShutdown(context->socket, SOCKET_SD_BOTH); } } //Return status code return error; }
/** * @brief Shutdown network connection * @param[in] context Pointer to the HTTP client context * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_client_transport.c#L164-L202
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpClientCloseConnection
void httpClientCloseConnection(HttpClientContext *context) { #if (HTTP_CLIENT_TLS_SUPPORT == ENABLED) //Release TLS context if(context->tlsContext != NULL) { tlsFree(context->tlsContext); context->tlsContext = NULL; } #endif //Close TCP connection if(context->socket != NULL) { socketClose(context->socket); context->socket = NULL; } }
/** * @brief Close network connection * @param[in] context Pointer to the HTTP client context **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_client_transport.c#L210-L227
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpClientSendData
error_t httpClientSendData(HttpClientContext *context, const void *data, size_t length, size_t *written, uint_t flags) { error_t error; #if (HTTP_CLIENT_TLS_SUPPORT == ENABLED) //TLS-secured connection? if(context->tlsContext != NULL) { //Send TLS-encrypted data error = tlsWrite(context->tlsContext, data, length, written, flags); } else #endif { //Transmit data error = socketSend(context->socket, data, length, written, flags); } pcaplog_ctx_t ctx; ctx.local_endpoint.ipv4 = 0; ctx.local_endpoint.port = context->socket->localPort; ctx.remote_endpoint.ipv4 = context->socket->remoteIpAddr.ipv4Addr; ctx.remote_endpoint.port = context->socket->remotePort; ctx.pcap_data = &context->private.pcap_data; pcaplog_write(&ctx, true, (const uint8_t *)data, length); //Return status code return error; }
/** * @brief Send data using the relevant transport protocol * @param[in] context Pointer to the HTTP client context * @param[in] data Pointer to a buffer containing the data to be transmitted * @param[in] length Number of bytes to be transmitted * @param[out] written Actual number of bytes written (optional parameter) * @param[in] flags Set of flags that influences the behavior of this function * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_client_transport.c#L240-L269
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpClientReceiveData
error_t httpClientReceiveData(HttpClientContext *context, void *data, size_t size, size_t *received, uint_t flags) { error_t error; #if (HTTP_CLIENT_TLS_SUPPORT == ENABLED) //TLS-secured connection? if(context->tlsContext != NULL) { //Receive TLS-encrypted data error = tlsRead(context->tlsContext, data, size, received, flags); } else #endif { //Receive data error = socketReceive(context->socket, data, size, received, flags); } pcaplog_ctx_t ctx; ctx.local_endpoint.ipv4 = 0; ctx.local_endpoint.port = context->socket->localPort; ctx.remote_endpoint.ipv4 = context->socket->remoteIpAddr.ipv4Addr; ctx.remote_endpoint.port = context->socket->remotePort; ctx.pcap_data = &context->private.pcap_data; pcaplog_write(&ctx, false, (const uint8_t *)data, *received); //Return status code return error; }
/** * @brief Receive data using the relevant transport protocol * @param[in] context Pointer to the HTTP client context * @param[out] data Buffer into which received data will be placed * @param[in] size Maximum number of bytes that can be received * @param[out] received Number of bytes that have been received * @param[in] flags Set of flags that influences the behavior of this function * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_client_transport.c#L282-L311
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpClientSaveSession
error_t httpClientSaveSession(HttpClientContext *context) { error_t error; //Initialize status code error = NO_ERROR; #if (HTTP_CLIENT_TLS_SUPPORT == ENABLED) //TLS-secured connection? if(context->tlsContext != NULL) { //Save TLS session error = tlsSaveSessionState(context->tlsContext, &context->tlsSession); } #endif //Return status code return error; }
/** * @brief Save TLS session * @param[in] context Pointer to the HTTP client context * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_client_transport.c#L320-L338
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpServerGetDefaultSettings
void httpServerGetDefaultSettings(HttpServerSettings *settings) { // The HTTP server is not bound to any interface settings->interface = NULL; // Listen to port 80 settings->port = HTTP_PORT; // HTTP server IP address settings->ipAddr = IP_ADDR_ANY; // Maximum length of the pending connection queue settings->backlog = HTTP_SERVER_BACKLOG; // Client connections settings->maxConnections = 0; settings->connections = NULL; // Specify the server's root directory osStrcpy(settings->rootDirectory, "/"); // Set default home page osStrcpy(settings->defaultDocument, "index.htm"); #if (HTTP_SERVER_TLS_SUPPORT == ENABLED) // TLS initialization callback function settings->tlsInitCallback = NULL; #endif #if (HTTP_SERVER_BASIC_AUTH_SUPPORT == ENABLED || HTTP_SERVER_DIGEST_AUTH_SUPPORT == ENABLED) // Random data generation callback function settings->randCallback = NULL; // HTTP authentication callback function settings->authCallback = NULL; #endif // CGI callback function settings->cgiCallback = NULL; // HTTP request callback function settings->requestCallback = NULL; // URI not found callback function settings->uriNotFoundCallback = NULL; }
/** * @brief Initialize settings with default values * @param[out] settings Structure that contains HTTP server settings **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L63-L102
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpServerInit
error_t httpServerInit(HttpServerContext *context, const HttpServerSettings *settings) { error_t error; uint_t i; HttpConnection *connection; // Debug message TRACE_INFO("Initializing HTTP server...\r\n"); // Ensure the parameters are valid if (context == NULL || settings == NULL) return ERROR_INVALID_PARAMETER; // Check settings if (settings->maxConnections == 0 || settings->connections == NULL) return ERROR_INVALID_PARAMETER; // Clear the HTTP server context osMemset(context, 0, sizeof(HttpServerContext)); // Save user settings context->settings = *settings; // Client connections context->connections = settings->connections; // Create a semaphore to limit the number of simultaneous connections if (!osCreateSemaphore(&context->semaphore, context->settings.maxConnections)) return ERROR_OUT_OF_RESOURCES; // Loop through client connections for (i = 0; i < context->settings.maxConnections; i++) { // Point to the structure representing the client connection connection = &context->connections[i]; // Initialize the structure osMemset(connection, 0, sizeof(HttpConnection)); // Create an event object to manage connection lifetime if (!osCreateEvent(&connection->startEvent)) return ERROR_OUT_OF_RESOURCES; } #if (HTTP_SERVER_TLS_SUPPORT == ENABLED && TLS_TICKET_SUPPORT == ENABLED) // Initialize ticket encryption context error = tlsInitTicketContext(&context->tlsTicketContext); // Any error to report? if (error) return error; #endif #if (HTTP_SERVER_DIGEST_AUTH_SUPPORT == ENABLED) // Create a mutex to prevent simultaneous access to the nonce cache if (!osCreateMutex(&context->nonceCacheMutex)) return ERROR_OUT_OF_RESOURCES; #endif // Open a TCP socket context->socket = socketOpen(SOCKET_TYPE_STREAM, SOCKET_IP_PROTO_TCP); // Failed to open socket? if (context->socket == NULL) return ERROR_OPEN_FAILED; // Set timeout for blocking functions error = socketSetTimeout(context->socket, INFINITE_DELAY); // Any error to report? if (error) return error; // Associate the socket with the relevant interface error = socketBindToInterface(context->socket, settings->interface); // Unable to bind the socket to the desired interface? if (error) return error; // Bind newly created socket to port 80 error = socketBind(context->socket, &settings->ipAddr, settings->port); // Failed to bind socket to port 80? if (error) return error; // Place socket in listening state error = socketListen(context->socket, settings->backlog); // Any failure to report? if (error) return error; // Successful initialization return NO_ERROR; }
/** * @brief HTTP server initialization * @param[in] context Pointer to the HTTP server context * @param[in] settings HTTP server specific settings * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L111-L200
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpServerStart
error_t httpServerStart(HttpServerContext *context) { uint_t i; HttpConnection *connection; // Make sure the HTTP server context is valid if (context == NULL) return ERROR_INVALID_PARAMETER; // Debug message TRACE_INFO("Starting HTTP server...\r\n"); // Loop through client connections for (i = 0; i < context->settings.maxConnections; i++) { // Point to the current session connection = &context->connections[i]; #if (OS_STATIC_TASK_SUPPORT == ENABLED) // Create a task using statically allocated memory connection->taskId = osCreateStaticTask("HTTP Connection", (OsTaskCode)httpConnectionTask, connection, &connection->taskTcb, connection->taskStack, HTTP_SERVER_STACK_SIZE, HTTP_SERVER_PRIORITY); #else // Create a task connection->taskId = osCreateTask("HTTP Connection", httpConnectionTask, &context->connections[i], HTTP_SERVER_STACK_SIZE, HTTP_SERVER_PRIORITY); #endif // Unable to create the task? if (connection->taskId == OS_INVALID_TASK_ID) return ERROR_OUT_OF_RESOURCES; } #if (OS_STATIC_TASK_SUPPORT == ENABLED) // Create a task using statically allocated memory context->taskId = osCreateStaticTask("HTTP Listener", (OsTaskCode)httpListenerTask, context, &context->taskTcb, context->taskStack, HTTP_SERVER_STACK_SIZE, HTTP_SERVER_PRIORITY); #else // Create a task context->taskId = osCreateTask("HTTP Listener", httpListenerTask, context, HTTP_SERVER_STACK_SIZE, HTTP_SERVER_PRIORITY); #endif // Unable to create the task? if (context->taskId == OS_INVALID_TASK_ID) return ERROR_OUT_OF_RESOURCES; // The HTTP server has successfully started return NO_ERROR; }
/** * @brief Start HTTP server * @param[in] context Pointer to the HTTP server context * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L208-L259
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpListenerTask
void httpListenerTask(void *param) { uint_t i; uint_t counter; uint16_t clientPort; IpAddr clientIpAddr; HttpServerContext *context; HttpConnection *connection; Socket *socket; // Task prologue osEnterTask(); // Retrieve the HTTP server context context = (HttpServerContext *)param; // Process incoming connections to the server for (counter = 1;; counter++) { // Debug message TRACE_INFO("Ready to accept a new connection...\r\n"); // Limit the number of simultaneous connections to the HTTP server osWaitForSemaphore(&context->semaphore, INFINITE_DELAY); // Loop through the connection table for (i = 0; i < context->settings.maxConnections; i++) { // Point to the current connection connection = &context->connections[i]; // Ready to service the client request? if (!connection->running) { // Accept an incoming connection socket = socketAccept(context->socket, &clientIpAddr, &clientPort); // Make sure the socket handle is valid if (socket != NULL) { // Debug message TRACE_INFO("Connection #%u established with client %s port %" PRIu16 "...\r\n", counter, ipAddrToString(&clientIpAddr, NULL), clientPort); // Reference to the HTTP server settings connection->settings = &context->settings; // Reference to the HTTP server context connection->serverContext = context; // Reference to the new socket connection->socket = socket; // Set timeout for blocking functions socketSetTimeout(connection->socket, HTTP_SERVER_TIMEOUT); // The client connection task is now running... connection->running = TRUE; // Service the current connection request osSetEvent(&connection->startEvent); } else { // Just for sanity osReleaseSemaphore(&context->semaphore); /* original code releases connection->serverContext, which is not set yet */ // osReleaseSemaphore(&connection->serverContext->semaphore); } // We are done break; } } } }
/** * @brief HTTP server listener task * @param[in] param Pointer to the HTTP server context **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L266-L338
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpConnectionTask
void httpConnectionTask(void *param) { error_t error; uint_t counter; HttpConnection *connection; // Task prologue osEnterTask(); // Point to the structure representing the HTTP connection connection = (HttpConnection *)param; // Endless loop while (1) { // Wait for an incoming connection attempt osWaitForEvent(&connection->startEvent, INFINITE_DELAY); // Initialize status code error = NO_ERROR; #if (HTTP_SERVER_TLS_SUPPORT == ENABLED) // TLS-secured connection? if (connection->settings->tlsInitCallback != NULL) { // Debug message TRACE_INFO("Initializing TLS session...\r\n"); // Start of exception handling block do { // Allocate TLS context connection->tlsContext = tlsInit(); // Initialization failed? if (connection->tlsContext == NULL) { // Report an error error = ERROR_OUT_OF_MEMORY; // Exit immediately break; } // Select server operation mode error = tlsSetConnectionEnd(connection->tlsContext, TLS_CONNECTION_END_SERVER); // Any error to report? if (error) break; // Bind TLS to the relevant socket error = tlsSetSocket(connection->tlsContext, connection->socket); // Any error to report? if (error) break; #if (TLS_TICKET_SUPPORT == ENABLED) // Enable session ticket mechanism error = tlsEnableSessionTickets(connection->tlsContext, TRUE); // Any error to report? if (error) break; // Register ticket encryption/decryption callbacks error = tlsSetTicketCallbacks(connection->tlsContext, tlsEncryptTicket, tlsDecryptTicket, &connection->serverContext->tlsTicketContext); // Any error to report? if (error) break; #endif // Invoke user-defined callback, if any if (connection->settings->tlsInitCallback != NULL) { // Perform TLS related initialization error = connection->settings->tlsInitCallback(connection, connection->tlsContext); // Any error to report? if (error) break; } // Establish a secure session error = tlsConnect(connection->tlsContext); // Any error to report? if (error) break; // End of exception handling block } while (0); } else { // Do not use TLS connection->tlsContext = NULL; } #endif // Check status code if (!error) { // Process incoming requests for (counter = 0; counter < HTTP_SERVER_MAX_REQUESTS; counter++) { // Debug message TRACE_INFO("Waiting for request...\r\n"); // Clear request header osMemset(&connection->request, 0, sizeof(HttpRequest)); // Clear response header osMemset(&connection->response, 0, sizeof(HttpResponse)); // Read the HTTP request header and parse its contents error = httpReadRequestHeader(connection); if (error == ERROR_INVALID_REQUEST && connection->response.contentLength > 4 && connection->buffer[0] == 0 && connection->buffer[1] == 0) { error = NO_ERROR; connection->response.byteCount = 0; while (error == NO_ERROR) { if (connection->response.contentLength > 0) error = connection->settings->requestCallback(connection, "*binary"); if (error != NO_ERROR) break; size_t length = 0; size_t pos = connection->response.byteCount; error = httpReceive(connection, &connection->buffer[pos], HTTP_SERVER_BUFFER_SIZE - pos, &length, SOCKET_FLAG_PEEK); // TODO connection->response.contentLength = length + pos; if (length == 0) osDelayTask(100); } continue; } // Any error to report? if (error) { // Debug message TRACE_WARNING("No HTTP request received or parsing error=%s...\r\n", error2text(error)); break; } #if (HTTP_SERVER_BASIC_AUTH_SUPPORT == ENABLED || HTTP_SERVER_DIGEST_AUTH_SUPPORT == ENABLED) // No Authorization header found? if (!connection->request.auth.found) { // Invoke user-defined callback, if any if (connection->settings->authCallback != NULL) { // Check whether the access to the specified URI is authorized connection->status = connection->settings->authCallback(connection, connection->request.auth.user, connection->request.uri); } else { // Access to the specified URI is allowed connection->status = HTTP_ACCESS_ALLOWED; } } // Check access status if (connection->status == HTTP_ACCESS_ALLOWED) { // Access to the specified URI is allowed error = NO_ERROR; } else if (connection->status == HTTP_ACCESS_BASIC_AUTH_REQUIRED) { // Basic access authentication is required connection->response.auth.mode = HTTP_AUTH_MODE_BASIC; // Report an error error = ERROR_AUTH_REQUIRED; } else if (connection->status == HTTP_ACCESS_DIGEST_AUTH_REQUIRED) { // Digest access authentication is required connection->response.auth.mode = HTTP_AUTH_MODE_DIGEST; // Report an error error = ERROR_AUTH_REQUIRED; } else { // Access to the specified URI is denied error = ERROR_NOT_FOUND; } #endif // Debug message TRACE_INFO("Sending HTTP response to the client...\r\n"); // Check status code if (!error) { // Default HTTP header fields httpInitResponseHeader(connection); // Invoke user-defined callback, if any if (connection->settings->requestCallback != NULL) { error = connection->settings->requestCallback(connection, connection->request.uri); } else { // Keep processing... error = ERROR_NOT_FOUND; } // Check status code if (error == ERROR_NOT_FOUND) { #if (HTTP_SERVER_SSI_SUPPORT == ENABLED) // Use server-side scripting to dynamically generate HTML code? if (httpCompExtension(connection->request.uri, ".stm") || httpCompExtension(connection->request.uri, ".shtm") || httpCompExtension(connection->request.uri, ".shtml")) { // SSI processing (Server Side Includes) error = ssiExecuteScript(connection, connection->request.uri, 0); } else #endif { // Set the maximum age for static resources connection->response.maxAge = HTTP_SERVER_MAX_AGE; // Send the contents of the requested page error = httpSendResponse(connection, connection->request.uri); } } // The requested resource is not available? if (error == ERROR_NOT_FOUND) { // Default HTTP header fields httpInitResponseHeader(connection); // Invoke user-defined callback, if any if (connection->settings->uriNotFoundCallback != NULL) { error = connection->settings->uriNotFoundCallback(connection, connection->request.uri); } } } // Check status code if (error) { // Default HTTP header fields httpInitResponseHeader(connection); // Bad request? if (error == ERROR_INVALID_REQUEST) { // Send an error 400 and close the connection immediately httpSendErrorResponse(connection, 400, "The request is badly formed"); } // Authorization required? else if (error == ERROR_AUTH_REQUIRED) { // Send an error 401 and keep the connection alive error = httpSendErrorResponse(connection, 401, "Authorization required"); } // Page not found? else if (error == ERROR_NOT_FOUND) { // Send an error 404 and keep the connection alive error = httpSendErrorResponse(connection, 404, "The requested page could not be found"); } } // Internal error? if (error) { // Close the connection immediately break; } // Check whether the connection is persistent or not if (!connection->request.keepAlive || !connection->response.keepAlive) { // Close the connection immediately break; } } } #if (HTTP_SERVER_TLS_SUPPORT == ENABLED) // Valid TLS context? if (connection->tlsContext != NULL) { // Debug message TRACE_INFO("Closing TLS session...\r\n"); // Gracefully close TLS session tlsShutdown(connection->tlsContext); // Release context tlsFree(connection->tlsContext); } #endif // Valid socket handle? if (connection->socket != NULL) { // Debug message TRACE_INFO("Graceful shutdown...\r\n"); // Graceful shutdown socketShutdown(connection->socket, SOCKET_SD_BOTH); // Debug message TRACE_INFO("Closing socket...\r\n"); // Close socket socketClose(connection->socket); } // Ready to serve the next connection request... connection->running = FALSE; // Release semaphore osReleaseSemaphore(&connection->serverContext->semaphore); } }
/** * @brief Task that services requests from an active connection * @param[in] param Structure representing an HTTP connection with a client **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L345-L666
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpWriteHeader
error_t httpWriteHeader(HttpConnection *connection) { error_t error; #if (NET_RTOS_SUPPORT == DISABLED) // Flush buffer connection->bufferPos = 0; connection->bufferLen = 0; #endif // Format HTTP response header error = httpFormatResponseHeader(connection, connection->buffer); // Check status code if (!error) { // Debug message TRACE_DEBUG("HTTP response header:\r\n%s", connection->buffer); // Send HTTP response header to the client error = httpSend(connection, connection->buffer, osStrlen(connection->buffer), HTTP_FLAG_DELAY); } // Return status code return error; }
/** * @brief Send HTTP response header * @param[in] connection Structure representing an HTTP connection * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L674-L700
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpReadStream
error_t httpReadStream(HttpConnection *connection, void *data, size_t size, size_t *received, uint_t flags) { error_t error; size_t n; // No data has been read yet *received = 0; // Chunked encoding transfer is used? if (connection->request.chunkedEncoding) { // Point to the output buffer char_t *p = data; // Read as much data as possible while (*received < size) { // End of HTTP request body? if (connection->request.lastChunk) return ERROR_END_OF_STREAM; // Acquire a new chunk when the current chunk // has been completely consumed if (connection->request.byteCount == 0) { // The size of each chunk is sent right before the chunk itself error = httpReadChunkSize(connection); // Failed to decode the chunk-size field? if (error) return error; // Any chunk whose size is zero terminates the data transfer if (!connection->request.byteCount) { // The user must be satisfied with data already on hand return (*received > 0) ? NO_ERROR : ERROR_END_OF_STREAM; } } // Limit the number of bytes to read at a time n = MIN(size - *received, connection->request.byteCount); // Read data error = httpReceive(connection, p, n, &n, flags); // Any error to report? if (error) return error; // Total number of data that have been read *received += n; // Number of bytes left to process in the current chunk connection->request.byteCount -= n; // The HTTP_FLAG_BREAK_CHAR flag causes the function to stop reading // data as soon as the specified break character is encountered if ((flags & HTTP_FLAG_BREAK_CRLF) != 0) { // Check whether a break character has been received if (p[n - 1] == LSB(flags)) break; } // The HTTP_FLAG_WAIT_ALL flag causes the function to return // only when the requested number of bytes have been read else if (!(flags & HTTP_FLAG_WAIT_ALL)) { break; } // Advance data pointer p += n; } } // Default encoding? else { // Return immediately if the end of the request body has been reached if (!connection->request.byteCount) return ERROR_END_OF_STREAM; // Limit the number of bytes to read n = MIN(size, connection->request.byteCount); // Read data error = httpReceive(connection, data, n, received, flags); // Any error to report? if (error) return error; // Decrement the count of remaining bytes to read connection->request.byteCount -= *received; } // Successful read operation return NO_ERROR; }
/** * @brief Read data from client request * @param[in] connection Structure representing an HTTP connection * @param[out] data Buffer where to store the incoming data * @param[in] size Maximum number of bytes that can be received * @param[out] received Number of bytes that have been received * @param[in] flags Set of flags that influences the behavior of this function * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L712-L807
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpWriteStream
error_t httpWriteStream(HttpConnection *connection, const void *data, size_t length) { error_t error; uint_t n; // Use chunked encoding transfer? if (connection->response.chunkedEncoding) { // Any data to send? if (length > 0) { char_t s[20]; // The chunk-size field is a string of hex digits indicating the size // of the chunk n = osSprintf(s, "%" PRIXSIZE "\r\n", length); // Send the chunk-size field error = httpSend(connection, s, n, HTTP_FLAG_DELAY); // Failed to send data? if (error) return error; // Send the chunk-data error = httpSend(connection, data, length, HTTP_FLAG_DELAY); // Failed to send data? if (error) return error; // Terminate the chunk-data by CRLF error = httpSend(connection, "\r\n", 2, HTTP_FLAG_DELAY); } else { // Any chunk whose size is zero may terminate the data // transfer and must be discarded error = NO_ERROR; } } // Default encoding? else { // The length of the body shall not exceed the value // specified in the Content-Length field length = MIN(length, connection->response.byteCount); // Send user data error = httpSend(connection, data, length, HTTP_FLAG_DELAY); // Decrement the count of remaining bytes to be transferred connection->response.byteCount -= length; } // Return status code return error; }
/** * @brief Write data to the client * @param[in] connection Structure representing an HTTP connection * @param[in] data Buffer containing the data to be transmitted * @param[in] length Number of bytes to be transmitted * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L817-L873
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpCloseStream
error_t httpCloseStream(HttpConnection *connection) { error_t error; // Use chunked encoding transfer? if (connection->response.chunkedEncoding) { // The chunked encoding is ended by any chunk whose size is zero error = httpSend(connection, "0\r\n\r\n", 5, HTTP_FLAG_NO_DELAY); } else { // Flush the send buffer error = httpSend(connection, "", 0, HTTP_FLAG_NO_DELAY); } // Return status code return error; }
/** * @brief Close output stream * @param[in] connection Structure representing an HTTP connection * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L881-L899
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpSendResponse
error_t httpSendResponse(HttpConnection *connection, const char_t *uri) { return httpSendResponseStream(connection, uri, false); }
/** * @brief Send HTTP response * @param[in] connection Structure representing an HTTP connection * @param[in] uri NULL-terminated string containing the file to be sent in response * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L908-L911
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpSendErrorResponse
error_t httpSendErrorResponse(HttpConnection *connection, uint_t statusCode, const char_t *message) { error_t error; size_t length; // HTML response template static const char_t template[] = "<!doctype html>\r\n" "<html>\r\n" "<head><title>Error %03d</title></head>\r\n" "<body>\r\n" "<h2>Error %03d</h2>\r\n" "<p>%s</p>\r\n" "</body>\r\n" "</html>\r\n"; // Compute the length of the response length = osStrlen(template) + osStrlen(message) - 4; // Check whether the HTTP request has a body if (osStrcasecmp(connection->request.method, "GET") && osStrcasecmp(connection->request.method, "HEAD") && osStrcasecmp(connection->request.method, "DELETE")) { // Drop the HTTP request body and close the connection after sending // the HTTP response connection->response.keepAlive = FALSE; } // Format HTTP response header connection->response.statusCode = statusCode; connection->response.contentType = mimeGetType(".htm"); connection->response.chunkedEncoding = FALSE; connection->response.contentLength = length; // Send the header to the client error = httpWriteHeader(connection); // Any error to report? if (error) return error; // Format HTML response osSprintf(connection->buffer, template, statusCode, statusCode, message); // Send response body error = httpWriteStream(connection, connection->buffer, length); // Any error to report? if (error) return error; // Properly close output stream error = httpCloseStream(connection); // Return status code return error; }
/** * @brief Send error response to the client * @param[in] connection Structure representing an HTTP connection * @param[in] statusCode HTTP status code * @param[in] message User message * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L1194-L1249
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpSendRedirectResponse
error_t httpSendRedirectResponse(HttpConnection *connection, uint_t statusCode, const char_t *uri) { error_t error; size_t length; // HTML response template static const char_t template[] = "<!doctype html>\r\n" "<html>\r\n" "<head><title>Moved</title></head>\r\n" "<body>\r\n" "<h2>Moved</h2>\r\n" "<p>This page has moved to <a href=\"%s\">%s</a>.</p>" "</body>\r\n" "</html>\r\n"; // Compute the length of the response length = osStrlen(template) + 2 * osStrlen(uri) - 4; // Check whether the HTTP request has a body if (osStrcasecmp(connection->request.method, "GET") && osStrcasecmp(connection->request.method, "HEAD") && osStrcasecmp(connection->request.method, "DELETE")) { // Drop the HTTP request body and close the connection after sending // the HTTP response connection->response.keepAlive = FALSE; } // Format HTTP response header connection->response.statusCode = statusCode; connection->response.location = uri; connection->response.contentType = mimeGetType(".htm"); connection->response.chunkedEncoding = FALSE; connection->response.contentLength = length; // Send the header to the client error = httpWriteHeader(connection); // Any error to report? if (error) return error; // Format HTML response osSprintf(connection->buffer, template, uri, uri); // Send response body error = httpWriteStream(connection, connection->buffer, length); // Any error to report? if (error) return error; // Properly close output stream error = httpCloseStream(connection); // Return status code return error; }
/** * @brief Send redirect response to the client * @param[in] connection Structure representing an HTTP connection * @param[in] statusCode HTTP status code (301 for permanent redirects) * @param[in] uri NULL-terminated string containing the redirect URI * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L1259-L1315
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpCheckWebSocketHandshake
bool_t httpCheckWebSocketHandshake(HttpConnection *connection) { #if (HTTP_SERVER_WEB_SOCKET_SUPPORT == ENABLED) error_t error; size_t n; // The request must contain an Upgrade header field whose value // must include the "websocket" keyword if (!connection->request.upgradeWebSocket) return FALSE; // The request must contain a Connection header field whose value // must include the "Upgrade" token if (!connection->request.connectionUpgrade) return FALSE; // Retrieve the length of the client's key n = osStrlen(connection->request.clientKey); // The request must include a header field with the name Sec-WebSocket-Key if (n == 0) return FALSE; // The value of the Sec-WebSocket-Key header field must be a 16-byte // value that has been Base64-encoded error = base64Decode(connection->request.clientKey, n, connection->buffer, &n); // Decoding failed? if (error) return FALSE; // Check the length of the resulting value if (n != 16) return FALSE; // The client's handshake is valid return TRUE; #else // WebSocket are not supported return FALSE; #endif }
/** * @brief Check whether the client's handshake is valid * @param[in] connection Structure representing an HTTP connection * @return TRUE if the WebSocket handshake is valid, else FALSE **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server.c#L1323-L1363
83d3b29cbfc74e8f76f48f8782646c8e464055b2
teddycloud
github_2023
toniebox-reverse-engineering
c
httpParseRequestLine
error_t httpParseRequestLine(HttpConnection *connection, char_t *requestLine) { error_t error; char_t *token; char_t *p; char_t *s; //The Request-Line begins with a method token token = osStrtok_r(requestLine, " \r\n", &p); //Unable to retrieve the method? if(token == NULL) return ERROR_INVALID_REQUEST; //The Method token indicates the method to be performed on the //resource identified by the Request-URI error = strSafeCopy(connection->request.method, token, HTTP_SERVER_METHOD_MAX_LEN); //Any error to report? if(error) return ERROR_INVALID_REQUEST; //The Request-URI is following the method token token = osStrtok_r(NULL, " \r\n", &p); //Unable to retrieve the Request-URI? if(token == NULL) return ERROR_INVALID_REQUEST; //Check whether a query string is present s = osStrchr(token, '?'); //Query string found? if(s != NULL) { //Split the string *s = '\0'; //Save the Request-URI error = httpDecodePercentEncodedString(token, connection->request.uri, HTTP_SERVER_URI_MAX_LEN); //Any error to report? if(error) return ERROR_INVALID_REQUEST; //Check the length of the query string if(osStrlen(s + 1) > HTTP_SERVER_QUERY_STRING_MAX_LEN) return ERROR_INVALID_REQUEST; //Save the query string osStrcpy(connection->request.queryString, s + 1); } else { //Save the Request-URI error = httpDecodePercentEncodedString(token, connection->request.uri, HTTP_SERVER_URI_MAX_LEN); //Any error to report? if(error) return ERROR_INVALID_REQUEST; //No query string connection->request.queryString[0] = '\0'; } //Redirect to the default home page if necessary if(!osStrcasecmp(connection->request.uri, "/")) osStrcpy(connection->request.uri, connection->settings->defaultDocument); //Clean the resulting path pathCanonicalize(connection->request.uri); //The protocol version is following the Request-URI token = osStrtok_r(NULL, " \r\n", &p); //HTTP version 0.9? if(token == NULL) { //Save version number connection->request.version = HTTP_VERSION_0_9; //Persistent connections are not supported connection->request.keepAlive = FALSE; } //HTTP version 1.0? else if(!osStrcasecmp(token, "HTTP/1.0")) { //Save version number connection->request.version = HTTP_VERSION_1_0; //By default connections are not persistent connection->request.keepAlive = FALSE; } //HTTP version 1.1? else if(!osStrcasecmp(token, "HTTP/1.1")) { //Save version number connection->request.version = HTTP_VERSION_1_1; //HTTP 1.1 makes persistent connections the default connection->request.keepAlive = TRUE; } //HTTP version not supported? else { //Report an error return ERROR_INVALID_REQUEST; } //Successful processing return NO_ERROR; }
/** * @brief Parse Request-Line * @param[in] connection Structure representing an HTTP connection * @param[in] requestLine Pointer to the string that holds the Request-Line * @return Error code **/
https://github.com/toniebox-reverse-engineering/teddycloud/blob/83d3b29cbfc74e8f76f48f8782646c8e464055b2/src/cyclone/cyclone_tcp/http/http_server_misc.c#L188-L293
83d3b29cbfc74e8f76f48f8782646c8e464055b2