/* Modify STR in-place. '%', CR and LF are always percent escaped, other characters may be percent escaped, always using uppercase hex, see https://www.gnupg.org/documentation/manuals/assuan.pdf */ static char * unescape_assuan(char *str) { char *s = str; while (s[0]) { if (s[0] == '%' && is_hex(s[1]) && is_hex(s[2])) { char *s2 = s; char val = hex_to_int(s[1]) * 16 + hex_to_int(s[2]); s2[0] = val; ++s2; while (s2[2]) { s2[0] = s2[2]; ++s2; } s2[0] = '\0'; } ++s; } return str; }
/* Converts the two input hex characters into an ascii char. */ static int hex_to_ascii(char a, char b) { int high = hex_to_int(a) * 16; int low = hex_to_int(b); return high + low; }
/* * get the values of malloc environ variables */ LOCAL void get_environ(void) { char *env; /* get the malloc_debug value */ env = (char *)getenv(DEBUG_ENVIRON); if (env != NULL) _malloc_debug = hex_to_int(env); /* get the malloc debug logfile name into a holding variable */ env = (char *)getenv(LOGFILE_ENVIRON); if (env != NULL) { (void)strcpy(log_path, env); malloc_logpath = log_path; } /* watch for a specific address and die when we get it */ env = (char *)getenv(ADDRESS_ENVIRON); if (env != NULL) { char *addp; addp = index(env, ':'); if (addp != NULL) { *addp = NULLC; address_count = atoi(addp + 1); } else address_count = 1; malloc_address = (char *)hex_to_int(env); } /* check the heap every X times */ env = (char *)getenv(INTERVAL_ENVIRON); if (env != NULL) check_interval = atoi(env); /* * start checking the heap after X iterations OR * start at a file:line combination */ env = (char *)getenv(START_ENVIRON); if (env != NULL) { char *startp; BIT_CLEAR(_malloc_debug, DEBUG_CHECK_HEAP); startp = index(env, ':'); if (startp != NULL) { *startp = NULLC; (void)strcpy(start_file, env); start_line = atoi(startp + 1); start_count = 0; } else start_count = atoi(env); } }
// See ConfigDlg.h for documentation of this method. void ConfigDlg::UpdateDataOfBootloaderConfigureArea(BOOL direction) { if (direction) { UpdateData(TRUE); // Update UI to CString m_bcaBinaries int length = m_bcaBinaries.GetLength(); LPWSTR buffer = m_bcaBinaries.GetBuffer(); char tempHigh, tempLow; int posBin = 0, posChar = 0; while ((posBin < 64) && (posChar < length)) { // Only convert legal characters. if (isxdigit(buffer[posChar * 2]) && isxdigit(buffer[posChar * 2 + 1])) { tempHigh = buffer[posChar * 2] & 0xFF; // change TCHAR to char, abandon the high bits. tempLow = buffer[posChar * 2 + 1] & 0xFF; // change TCHAR to char, abandon the high bits. m_bcaData[posBin] = ((hex_to_int(tempHigh) & 0xFF) << 4) | (hex_to_int(tempLow) & 0xFF); posBin++; posChar++; } else { // Skip the illegal character pairs. posChar++; } } m_bcaBinaries.ReleaseBuffer(); } else { LPTSTR buffer = m_bcaBinaries.GetBuffer(128 + 2 * 4 + 1); // 128 for 128 BCA characters // 2 * 4 for enter characters("\r\n") each line // 1 byte more for for terminator("\0") int posBin = 0, posChar = 0; for (; posBin < 64; posChar++, posBin++) { // 32 characters each line. if ((!(posBin % 0x10)) && (posBin != 0)) { // Add "\r\n" at the end of each line buffer[posChar * 2] = '\r'; buffer[posChar * 2 + 1] = '\n'; posChar++; } buffer[posChar * 2] = int_to_hex(m_bcaData[posBin] >> 4); buffer[posChar * 2 + 1] = int_to_hex(m_bcaData[posBin]); } buffer[posChar * 2] = '\0'; m_bcaBinaries.ReleaseBuffer(); UpdateData(FALSE); // Update CString m_bcaBinaries to UI } }
/* * Function to unparse the hexadecimal to byte char. * Input:char *str -- Hexadecimal hash value * Output:DIGEST -- byte char of hash. */ DIGEST *unparse(char *str, int len) { DIGEST *digest = (DIGEST *)calloc(1, len); int index; for (index = 0; index < len * 2; index += 2) { digest[index / 2] = hex_to_int(str[index]) * 16 + hex_to_int(str[index + 1]); } return digest; }
static svn_boolean_t hex_decode(unsigned char *hashval, const char *hexval) { int i, h1, h2; for (i = 0; i < APR_MD5_DIGESTSIZE; i++) { h1 = hex_to_int(hexval[2 * i]); h2 = hex_to_int(hexval[2 * i + 1]); if (h1 == -1 || h2 == -1) return FALSE; hashval[i] = (unsigned char)((h1 << 4) | h2); } return TRUE; }
int handle_msg(char *msg, int bytes) { int length, i; char *end; ENVIRAHDR *hdr; switch (msg[0]) { // These occur at message boundaries so we ignore them case 0x0A: return 1; case 0x0D: return 1; case '>': return 1; // We discard these messages at the moment case '[': return bytes; // One of the message types we know. Qualify and decode the message. case 'H': case 'M': case 'L': // See if we have a complete message terminated with a newline. The spec // says we should get 0x0D 0x0A, but I'm getting 0x0A 0x0A on mine. end = memchr(msg, 0x0A, bytes); if (!end) return 0; // We need at least 17 bytes to contain even a 0-byte-payload message length = end - msg; if (length < 17) { return bytes; } // Decode the message. We don't bother with the checksum right now. hdr = (ENVIRAHDR *) msg; emsg.priority = (hdr->priority == 'H') ? 0x00 : (hdr->priority == 'M' ? 0x40 : 0x80); emsg.type = hex_to_int(hdr->type, sizeof(hdr->type)); emsg.instance = hex_to_int(hdr->instance, sizeof(hdr->instance)); emsg.command = (hdr->command == 'Q') ? 0x00 : (hdr->command == 'R' ? 0x40 : 0x80); emsg.length = hex_to_int(hdr->length, sizeof(hdr->length)); for (i = 0; i < emsg.length && i < sizeof(emsg.payload); i++) { emsg.payload[i] = hex_to_int(&hdr->payload[i * 3], 2); } process_enviracom(&emsg); return length; // Unknown message - probably started mid-stream. Discard to sync up default: return bytes; } }
static uint8_t *decode_html(uint8_t *data, uint64_t data_length, uint64_t *out_length) { buffer_t *b = buffer_create(BO_HOST); uint64_t i = 0; while(i < data_length) { /* If the character is a '%' and we aren't at the end of the string, decode * the hex character and add it to the string. * * The typecasts to 'int' here are to fix warnings from cygwin. */ if(data[i] == '%' && (i + 2) < data_length && isxdigit((int)data[i + 1]) && isxdigit((int)data[i + 2])) { /* Add the new character to the string as a uint8_t. */ buffer_add_int8(b, hex_to_int(&data[i] + 1)); /* We consumed three digits here. */ i += 3; } else if(data[i] == '+') { /* In html encoding, a '+' is a space. */ buffer_add_int8(b, ' '); i++; } else { /* If it's not %NN or +, it's just a raw number.k */ buffer_add_int8(b, data[i]); i++; } } return buffer_create_string_and_destroy(b, out_length); }
static uint8_t *decode_hex(uint8_t *data, uint64_t data_length, uint64_t *out_length) { buffer_t *b = buffer_create(BO_HOST); uint64_t i = 0; /* If we wind up with an odd number of characters, the final character is * ignored. */ while(i + 1 < data_length) { /* Skip over and ignore non-hex digits. */ if(!isxdigit(data[i]) || !isxdigit(data[i+1])) { i++; continue; } /* Add the new character to the string as a uint8_t. */ buffer_add_int8(b, hex_to_int(&data[i])); /* We consumed three digits here. */ i += 2; } return buffer_create_string_and_destroy(b, out_length); }
int decode_hex(const char *str, unsigned char *ch) { int i; *ch = 0; for(i = 0; i < 2; i++) { if(!isxdigit(str[i])) { break; } *ch = *ch << 4; *ch = *ch | hex_to_int(str[i]); } if(i == 0) { printf("Missing following hex characters\n"); return 0; } if(*ch == 0) { printf("Invalid hex character (not allowed NULs)\n"); return 0; } return i; }
/* Detect chunked upload progress */ static int all_chunks_uploaded(char *buffer, int size, long *chunk_size_pos) { int chunk_size, len; char *end; if (*chunk_size_pos >= size) { return -1; } if ((end = strstr(buffer + *chunk_size_pos, "\r\n")) == NULL) { return 0; } *end = '\0'; chunk_size = hex_to_int(buffer + *chunk_size_pos); *end = '\r'; if (chunk_size == -1) { return -1; } len = (end - buffer) + chunk_size + 4; if (chunk_size == 0) { if (size >= len) { return 1; } } else if (size > len) { *chunk_size_pos = len; return all_chunks_uploaded(buffer, size, chunk_size_pos); } return 0; }
static int parse_numeric_literal(parser_ctx_t *ctx, literal_t **literal) { LONG l, d; l = *ctx->ptr++ - '0'; if(!l) { if(*ctx->ptr == 'x' || *ctx->ptr == 'X') { if(++ctx->ptr == ctx->end) { ERR("unexpected end of file\n"); return 0; } while(ctx->ptr < ctx->end && (d = hex_to_int(*ctx->ptr)) != -1) { l = l*16 + d; ctx->ptr++; } if(ctx->ptr < ctx->end && is_identifier_char(*ctx->ptr)) { WARN("unexpected identifier char\n"); return lex_error(ctx, JS_E_MISSING_SEMICOLON); } *literal = new_double_literal(ctx, l); return tNumericLiteral; } if(isdigitW(*ctx->ptr)) { unsigned base = 8; const WCHAR *ptr; double val = 0; for(ptr = ctx->ptr; ptr < ctx->end && isdigitW(*ptr); ptr++) { if(*ptr > '7') { base = 10; break; } } do { val = val*base + *ctx->ptr-'0'; }while(++ctx->ptr < ctx->end && isdigitW(*ctx->ptr)); /* FIXME: Do we need it here? */ if(ctx->ptr < ctx->end && (is_identifier_char(*ctx->ptr) || *ctx->ptr == '.')) { WARN("wrong char after octal literal: '%c'\n", *ctx->ptr); return lex_error(ctx, JS_E_MISSING_SEMICOLON); } *literal = new_double_literal(ctx, val); return tNumericLiteral; } if(is_identifier_char(*ctx->ptr)) { WARN("wrong char after zero\n"); return lex_error(ctx, JS_E_MISSING_SEMICOLON); } } return parse_double_literal(ctx, l, literal); }
int load_motos1(char *filename) { char buf[201]; char *r; int num_bytes,i,p,done=0; long start_addr; unsigned char value; FILE *fi; printf("loading %s\n", filename); fi=fopen(filename,"r"); if(fi==NULL) { printf("can't open it, sorry.\n"); return(0); } r = fgets(buf,200,fi); while(!done) { /* read len */ /* 2 bytes of addr, 1 byte is checksum */ num_bytes = (16*hex_to_int(buf[2])+hex_to_int(buf[3]))-3; /* read addr */ start_addr=0; for(p=4,i=0;i<4;i++) start_addr = (start_addr<<4) + hex_to_int(buf[p++]); /* read data */ for(i=0;i<num_bytes;i++) { value = 16*hex_to_int(buf[p])+hex_to_int(buf[p+1]); p+=2; set_memb(start_addr+i,value); // printf("0x%08x: 0x%02x\n",start_addr+i,value); } /* check for ending */ if(!strncmp("S9",buf,2)) { break; /* done */ } r = fgets(buf,200,fi); if(feof(fi))done=1; } fclose(fi); return(1); }
static int unescape_character (const char *scanner) { int first_digit; int second_digit; first_digit = hex_to_int (*scanner++); if (first_digit < 0) { return -1; } second_digit = hex_to_int (*scanner++); if (second_digit < 0) { return -1; } return (first_digit << 4) | second_digit; }
void http_decode_url(char *url) { char *out; char c; out = url; while ('\0' != (c = *url)) { if (c == '%' && *(url + 1) != '\0' && *(url + 2) != '\0') { *out = (char)(hex_to_int(*(url + 1)) * 16 + hex_to_int(*(url + 2))); ++out; url += 2; } else { *out = c; ++out; ++url; } } *out = '\0'; }
char* hexToString(char* in) { int index; char* ascii = malloc(sizeof(char)*4096); int high; int low; int c; for (index = 0; index<strlen(in); index = index+2) { high = hex_to_int(in[index]) * 16; low = hex_to_int(in[index+1]); c = (high+low); // printf("%c", c); if (index == 0) ascii[0] = c; else ascii[index/2] = c; } ascii[(index+1)/2] = '\0'; return ascii; }
static void test_hex_to_int(void) { int i; char buffer[] = "AA\0"; printf("Testing hex_to_int...\n"); for(i = 0; i < 256; i++) { sprintf(buffer, "%02x", i); test_check_integer("hex_to_int", hex_to_int((uint8_t*)buffer), i); } }
void LED_Array::fetch_leds(void) { String msg = bluetooth.read_string(); bluetooth.write_string(msg); msg.trim(); int num_leds = (msg.length() - 1 > array_size) ? array_size: msg.length() - 1; bluetooth.write_string("Number of leds: " + String(num_leds)); if (msg.length()) { pattern = hex_to_int(msg[0]); bluetooth.write_string("Pattern: " + String(pattern)); } for (int i = 0; i < num_leds; i++) { int current_val = hex_to_int(msg[i+1]); led_array[i].red = current_val & 4 ? 255 : 0; led_array[i].green = current_val & 2 ? 255 : 0; led_array[i].blue = current_val & 1 ? 255 : 0; bluetooth.write_string("LED" + String(i) + " RED:" + String(led_array[i].red) + " GREEN:" + String(led_array[i].green) + " BLUE:" + String(led_array[i].blue)); } }
static int decrypt_password(unsigned char *secret, int keybits, char *buf, int bufsize, char *encrypted) { size_t ciphertextlen, datalen; unsigned char iv[BLOCK_SIZE]; rijndaelcbc *c; int i, j; datalen = strlen(encrypted); if(datalen % 2 != 0) return 1; if(datalen < BLOCK_SIZE * 2 * 2) return 2; if(!hex_to_int(encrypted, iv, BLOCK_SIZE)) return 3; ciphertextlen = (datalen - (BLOCK_SIZE * 2)) / 2; if(ciphertextlen > bufsize || ciphertextlen % BLOCK_SIZE != 0) return 4; if(!hex_to_int(encrypted + BLOCK_SIZE * 2, (unsigned char *)buf, ciphertextlen)) return 5; c = rijndaelcbc_init(secret, keybits, iv, 1); for(i=0;i<ciphertextlen;i+=BLOCK_SIZE) { char *p = &buf[i]; unsigned char *r = rijndaelcbc_decrypt(c, (unsigned char *)p); memcpy(p, r, BLOCK_SIZE); for(j=0;j<BLOCK_SIZE;j++) { if(*(p + j) == '\0') { rijndaelcbc_free(c); return 0; } } } rijndaelcbc_free(c); return 6; }
/* Prevent cross-site scripting. */ int prevent_xss(t_session *session) { int result = 0; short low, high; char *str, value; if ((str = session->vars) == NULL) { return 0; } while (*str != '\0') { if ((value = *str) == '%') { if ((high = hex_to_int(*(str + 1))) != -1) { if ((low = hex_to_int(*(str + 2))) != -1) { value = (char)(high<<4) + low; } } } if ((value == '\"') || (value == '<') || (value == '>') || (value == '\'')) { *str = '_'; result += 1; } str++; } if (result > 0) { log_exploit_attempt(session, "XSS", session->vars); #ifdef ENABLE_TOMAHAWK increment_counter(COUNTER_EXPLOIT); #endif #ifdef ENABLE_MONITOR if (session->config->monitor_enabled) { monitor_counter_exploit_attempt(session); } #endif } return result; }
static void unescape_path_component (gchar * comp) { guint len = strlen (comp); guint i; for (i = 0; i + 2 < len; i++) if (comp[i] == '%') { int a, b; a = hex_to_int (comp[i + 1]); b = hex_to_int (comp[i + 2]); /* The a||b check is to ensure that the byte is not '\0' */ if (a >= 0 && b >= 0 && (a || b)) { comp[i] = (gchar) (a * 16 + b); memmove (comp + i + 1, comp + i + 3, len - i - 3); len -= 2; comp[len] = '\0'; } } }
static rc_t MD5SumExtract(const char* str, uint8_t digest[16]) { rc_t rc = 0; int i = 0; /* parse checksum */ for ( i = 0; i < 16; ++ i ) { int l, u = hex_to_int ( str [ i + i + 0 ] ); l = hex_to_int ( str [ i + i + 1 ] ); if ( u < 0 || l < 0 ) { rc = RC ( rcFS, rcXmlDoc, rcReading, rcFormat, rcInvalid ); break; } digest [ i ] = ( uint8_t ) ( ( u << 4 ) | l ); } return rc; }
static void unescape_url_component(tu_string* str) // Do URL unescaping on a URL component. I.e. convert the hex code // "%xx" to the corresponding byte, and change '+' to ' '. { tu_string out; for (int i = 0; i < str->length(); i++) { char c = (*str)[i]; if (c == '%' && i + 2 < str->length()) { // Interpret the next two chars as hex digits. char digit_hi = (*str)[i + 1]; char digit_lo = (*str)[i + 2]; int val_hi = hex_to_int(digit_hi); int val_lo = hex_to_int(digit_lo); if (val_hi < 0 || val_lo < 0) { // Invalid hex digits. Pass the '%' // straight through and don't consume the // two following chars. out += c; } else { char encoded = (val_hi << 4) | (val_lo); if (encoded > 0) { out += encoded; } i += 2; } } else if (c == '+') { // '+' is turned into a space. out += ' '; } else { // Pass this character straight through. out += c; } } *str = out; }
void QUrl::decode( QString& url ) { if ( url.isEmpty() ) return; int newlen = 0; QCString curl = url.utf8(); int oldlen = curl.length(); QCString newUrl(oldlen); int i = 0; while ( i < oldlen ) { uchar c = (uchar)curl[ i++ ]; if ( c == '%' && i <= oldlen - 2 ) { c = hex_to_int( (uchar)curl[ i ] ) * 16 + hex_to_int( (uchar)curl[ i + 1 ] ); i += 2; } newUrl [ newlen++ ] = c; } newUrl.truncate( newlen ); url = QString::fromUtf8(newUrl.data()); }
static bool hex_decode(const char *hex, uint8_t **raw, size_t *len) { size_t hexlen = strlen(hex); uint8_t *p; if (hexlen == 0 || (hexlen % 2) != 0) return (false); *len = hexlen / 2; p = *raw = malloc(*len); if (*raw == NULL) return (false); while (hexlen != 0) { uint8_t val[2]; if (!hex_to_int(*hex, &val[0])) goto err; hex++; if (!hex_to_int(*hex, &val[1])) goto err; hex++; *p = (val[0] << 4) | val[1]; p++; hexlen -= 2; } return (true); err: free(*raw); return (false); }
char* recv_message(int sockfd, SA *peeraddr, socklen_t *peeraddr_len) { /* Read the message length, without discarding the message. */ char msg_len_hex[4]; Recvfrom(sockfd, msg_len_hex, sizeof(msg_len_hex), MSG_PEEK, peeraddr, peeraddr_len); unsigned int msg_len = hex_to_int(msg_len_hex); /* Read the whole message, including the length */ char *message = malloc(msg_len); Recvfrom(sockfd, message, msg_len, 0, peeraddr, peeraddr_len); message[msg_len - 1] = 0; return message; }
static int parse_hex_literal(parser_ctx_t *ctx, LONG *ret) { const WCHAR *begin = ctx->ptr; LONG l = 0, d; while((d = hex_to_int(*++ctx->ptr)) != -1) l = l*16 + d; if(begin + 9 /* max digits+1 */ < ctx->ptr || *ctx->ptr != '&') { FIXME("invalid literal\n"); return 0; } ctx->ptr++; *ret = l; return (short)l == l ? tShort : tLong; }
static inline uint64_t parse_btaddr (const wchar_t *s) { uint64_t addr = 0; for (int i = 0; i < 18; i++) { if (i == 17) { if (s[i] != '\0') { return INVALID_BTADDR; } else continue; } if ((i % 3) == 2) { if (s[i] != ':') { return INVALID_BTADDR; } else continue; } unsigned char ret = hex_to_int (s[i]); if (ret == 0xff) { return INVALID_BTADDR; } addr <<= 4; addr |= ret; } return addr; }
/* Merge chunks to one single content block */ static long merge_chunks(char *buffer, long size, long *bytes_in_buffer) { long chunk_size, chunk_hf_len, content_length = 0; char *end, *destination; destination = buffer; do { if ((end = strstr(buffer, "\r\n")) == NULL) { return -1; } *end = '\0'; chunk_size = hex_to_int(buffer); *end = '\r'; if (chunk_size == -1) { return -1; } chunk_hf_len = end + 4 - buffer; if (chunk_hf_len + chunk_size > size) { return -1; } if (chunk_size == 0) { size -= chunk_hf_len; if (size > 0) { memmove(destination, end + 4, size); } *bytes_in_buffer -= chunk_hf_len; *(destination + size) = '\0'; } else { memmove(destination, end + 2, chunk_size); destination += chunk_size; size -= chunk_hf_len + chunk_size; buffer += chunk_hf_len + chunk_size; content_length += chunk_size; *bytes_in_buffer -= chunk_hf_len; } } while (chunk_size > 0); return content_length; }
// Dans ce test, on va s'assurer que l'utilisateur n'accède pas à la mémoire située après la fin de la chaine de caractères // @strcasecmp:test_hex_to_int5 => [hex_to_int accède à une adresse mémoire à droite de la zone mémoire de la chaine de caractères passée en argument.] void test_hex_to_int5(void) { char* hex1 = NULL; //On cherche à allouer 2 pages de la mémoire, la première avec le droit d'écriture et de lecture void *ptr = mmap(NULL, getpagesize()*2, PROT_READ | PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); if (ptr == MAP_FAILED) { CU_FAIL("La mémoire n'a pas pu être allouée pour le test test_hex_to_int5."); return; } // On protège ensuite la deuxième page mémoire en enlevant les droits de lecture et écriture mprotect(ptr+getpagesize(), getpagesize(), PROT_NONE); // On écrit à la fin de la première page mémoire la chaine "00A1C345" hex1 = (char*) ptr+getpagesize()-9; strcpy(hex1, "0011C345"); /* Si le code de l'utilisateur accède à de la mémoire située après le caractère de fin \0, * autrement dit la mémoire protégée de la seconde page, un segfault sera envoyé. * La mécanique utilisée ici permet d'"attraper" un segfault sans que tout le programme ne plante */ //On enregistre un signal handler. Cette fonction sera exécutée par le programme lorsque //le code produira une segmentation fault (ce qui lance le signal SIGSEGV). if (signal(SIGSEGV, sig_handler1) == SIG_ERR) { CU_FAIL("Impossible d'enregistrer un signal handler."); return; } //On définit ici un jump avec le label label_test_hex_to_int5 qui attend le paramètre 0 (par défaut) if(setjmp(label_test_hex_to_int5)==0) { CU_ASSERT_TRUE( hex_to_int(hex1) == 1164101); } else { //On a reçu un autre paramètre que 0, autrement dit le code a exécuté sig_handler //On a donc intercepté une segmentation fault, donc le code de l'utilisateur est fautif. CU_ASSERT_TRUE(0); } //On enlève le signal handler précédemment assigné à SIGSEGV signal(SIGSEGV, SIG_DFL); //On libère la mémoire précédemment allouée munmap(ptr, getpagesize()*2); }