Beispiel #1
0
static int	set_color_with_pc(t_gui *gui,
				  t_corewar *core,
				  int i)
{
  SDL_Color	fg_color;
  char		str[3];

  fg_color.r = 0;
  fg_color.g = 0;
  fg_color.b = 0;
  fg_color.unused = 0;
  if (is_pc(core, gui, i) != 0)
    gui->byte_arena = TTF_RenderText_Shaded(gui->font,
					    hex_to_str(core->arena[i],
						       &str[0]),
					    fg_color,
					    gui->my_color);
  else
    gui->byte_arena = TTF_RenderText_Solid(gui->font,
  					   hex_to_str(core->arena[i],
						      &str[0]),
  					   gui->my_color);
  if (gui->byte_arena == NULL)
    return (my_putstr("error: TTF_RenderText\n", 2));
  return (0);
}
jstring Java_com_hid_usbjni_UsbJni_UsbBulkWriteRead(JNIEnv *env, jobject obj, jstring content)
{
	int r;
	char scmd[1024] = {0}, rmsg[1024] = {0};
	unsigned char sbuf[1024], rbuf[1024];
	unsigned int slen, rlen = 0;
	INIT_RETURN_VALUE();

	strncpy(scmd, str, sizeof(scmd) - 1);
	r = str_to_hex(scmd, sbuf, sizeof(sbuf));
	if (r <= 0) {
		pdebug("str_to_hex error: r = %d\n", r);
		snprintf(rmsg, sizeof(rmsg), "str_to_hex error: ret = %d", r);
		r = -1;
		goto out;
	}
	slen = r;

	r = HID_write_read(NULL, sbuf, slen, rbuf, &rlen);
	if (r != 0) {
		snprintf(rmsg, sizeof(rmsg), "HID_write_read error: ret = %d", r);
		goto out;
	}

	if (NULL == hex_to_str(rbuf, rlen, rmsg, sizeof(rmsg))) {
		snprintf(rmsg, sizeof(rmsg), "hex_to_str error");
	}

	r = 0;
out:
	/* 通知虚拟机本地代码不再需要通过 str 访问 Java 字符串。 */
	(*env)->ReleaseStringUTFChars(env, content, (const char *)str);
	RETURN_VAL(r, rmsg);
}
Beispiel #3
0
std::string Tox_Dispatcher::get_self_id()
{
    uint8_t addr[TOX_ADDRESS_SIZE];
    lock.lock();
        tox_self_get_address(tox, addr);
    lock.unlock();
    return hex_to_str(addr, TOX_ADDRESS_SIZE);
}
Beispiel #4
0
 const char *scan_range2str(const common::ObRange &scan_range)
 {
   static const int64_t BUFFER_SIZE = 1024;
   static __thread char buffers[2][BUFFER_SIZE];
   static __thread int64_t i = 0;
   char *buffer = buffers[i++ % 2];
   buffer[0] = '\0';
   const char *start_bound = scan_range.border_flag_.inclusive_start() ? "[" : "(";
   const char *end_bound = scan_range.border_flag_.inclusive_end() ? "]" : ")";
   if (scan_range.border_flag_.is_min_value())
   {
     if (scan_range.border_flag_.is_max_value())
     {
       snprintf(buffer, BUFFER_SIZE, "table_id=%lu %sMIN,MAX%s", scan_range.table_id_, start_bound, end_bound);
     }
     else
     {
       char hex_buffer[BUFFER_SIZE] = {'\0'};
       hex_to_str(scan_range.end_key_.ptr(), scan_range.end_key_.length(), hex_buffer, BUFFER_SIZE);
       snprintf(buffer, BUFFER_SIZE, "table_id=%lu %sMIN,%s%s", scan_range.table_id_, start_bound, hex_buffer, end_bound);
     }
   }
   else
   {
     if (scan_range.border_flag_.is_max_value())
     {
       char hex_buffer[BUFFER_SIZE] = {'\0'};
       hex_to_str(scan_range.start_key_.ptr(), scan_range.start_key_.length(), hex_buffer, BUFFER_SIZE);
       snprintf(buffer, BUFFER_SIZE, "table_id=%lu %s%s,MAX%s", scan_range.table_id_, start_bound, hex_buffer, end_bound);
     }
     else
     {
       char hex_buffers[2][BUFFER_SIZE];
       hex_buffers[0][0] = '\0';
       hex_to_str(scan_range.start_key_.ptr(), scan_range.start_key_.length(), hex_buffers[0], BUFFER_SIZE);
       hex_buffers[1][0] = '\0';
       hex_to_str(scan_range.end_key_.ptr(), scan_range.end_key_.length(), hex_buffers[1], BUFFER_SIZE);
       snprintf(buffer, BUFFER_SIZE, "table_id=%lu %s%s,%s%s", scan_range.table_id_, start_bound, hex_buffers[0], hex_buffers[1], end_bound);
     }
   }
   return buffer;
 }
Beispiel #5
0
static unsigned char *
hex_str_to_bin(const char *hexstr, int *modulus_len)
{
    int len;
    unsigned char *result;
    int i = 0, j = 0;
    char val1, val2;

    len = strlen(hexstr);

    if ((len & 1) != 0) {
        fprintf(stderr, "Got an odd number of hex digits (%d).\n", len);
        return NULL;
    }

    result = malloc(len / 2);
    i = 0;
    j = 0;

    while (i < len) {
        val1 = hex_to_str(hexstr[i]);
        if (val1 < 0) {
            fprintf(stderr, "Illegal hex character '%c'.", hexstr[i]);
            free(result);
            return NULL;
        }
        i++;
        val2 = hex_to_str(hexstr[i]);
        if (val2 < 0) {
            fprintf(stderr, "Illegal hex character '%c'.", hexstr[i]);
            free(result);
            return NULL;
        }
        i++;
        result[j++] = (val1 << 4) | val2;
    }
    *modulus_len = j;

    return result;
}
void setArguments(){
    /*
     * Verification os file in
     */
    if (fileIn == NULL){
        fprintf(stderr, "There is no input file.\n");
        exit(-1);
    }

    /*
     * Verification o number of bits.
     * Number default: 1.
     */
    if (nbBits == -1){
        nbBits = 1;
    }
    else{
        if(nbBits>8 || nbBits <1){
            fprintf(stderr, "Not possible to pattern a message with this number of bits\n");
            exit(-1);
        }
    }

    /*
     * Verification of pattern
     * Default pattern: Direct.
     */
    if(pattern == NULL){
        pattern = "DIRECT";
        patternInt = 1;
    }
    else{
        flag = validatePattern();
        switch (flag){
            case -1:
                fprintf(stderr, "Not a valid pattern\n");
                exit(-1);
            case 1:
                patternInt = flag; //Direct Pattern
                break;
            case 2:
                patternInt = flag; //Inverse
                break;
            case 3:
                fprintf(stderr, "External spiral pattern not implemented\n");
                exit(-3);
            case 4:
                fprintf(stderr, "Internal spiral pattern not implemented\n");
                exit(-4);
        }
    }

    /**
     * Setting and validation os Channels
     * Default: Red,Green,Blue
     */
    if (channels == NULL){
        firstChannel = 2;
        secondChannel = 1;
        thirdChannel = 0;
    }else{
        setChannels();
    }

    /**
     * Validation of Magic Number
     * Default: 48454C50
     */
    if(magicHexa == NULL){
        magicHexa = "48454C50";
        magic = hex_to_str(magicHexa); // magic = "HELP"
    }else{
        magic = hex_to_str(magicHexa);
    }

    /**
     * Validation of Output
     * Default: Standart (Console)
     */
    if(fileOut != NULL){
        isStandard = false;
    }
    else {
        isStandard = true;
        fileOut = "output.txt";
    }

    /**
     * Validation of the format of input
     * If there is no format, the program will detect.
     * If the format of the image its different of the argument or it is not a format accepted,
     * the program ends/error.
     */

    img = cvLoadImage(fileIn, 1); // Second parameter == 1 (RGB) || == 0 (GREY)
    if (img){ //Try to load the image by OpenCv
        if(formatIn == NULL){
            int format = detect_format(fileIn);
            if (format == -1){
                fprintf(stderr, "Not possible to detect format\n");
                exit(-1);
            }
        }
        else {
            flag = validateFormat();
            switch (flag) {
                case 0: //Accepted
                    break;
                case -1:
                    fprintf(stderr, "%s is not a format accepted\n", formatIn);
                    exit(-1);
                case -2:
                    fprintf(stderr, "This format is not the format of the image\n");
                    exit(-2);
                case -3:
                    fprintf(stderr, "Not a format valid\n");
                    exit(-2);
            }
        }
    }else{
        fprintf(stderr, "Could not open the file\n");
        exit(-3);
    }
}
Beispiel #7
0
static int
load_rite_irep_record(mrb_state *mrb, RiteFILE* rfp, unsigned char* dst, uint32_t* len)
{
  int i;
  uint32_t blocklen;
  uint16_t offset, pdl, snl, clen;
  unsigned char hex2[2], hex4[4], hex8[8], hcrc[4];
  unsigned char *pStart;
  char *char_buf;
  uint16_t buf_size =0;

  buf_size = MRB_DUMP_DEFAULT_STR_LEN;
  if ((char_buf = (char *)mrb_malloc(mrb, buf_size)) == NULL)
    goto error_exit;

  pStart = dst;

  //IREP HEADER BLOCK
  *dst = rite_fgetc(rfp, TRUE);                         //record identifier
  if (*dst != RITE_IREP_IDENFIFIER)
    return MRB_DUMP_INVALID_IREP;
  dst += sizeof(unsigned char);
  *dst = rite_fgetc(rfp, TRUE);                         //class or module
  dst += sizeof(unsigned char);
  rite_fgets(rfp, hex4, sizeof(hex4), TRUE);            //number of local variable
  dst += hex_to_bin16(dst, hex4);
  rite_fgets(rfp, hex4, sizeof(hex4), TRUE);            //number of register variable
  dst += hex_to_bin16(dst, hex4);
  rite_fgets(rfp, hex4, sizeof(hex4), TRUE);            //offset of isec block
  offset = hex_to_uint16(hex4);
  rite_fgets(rfp, hcrc, sizeof(hcrc), TRUE);            //header CRC
  memset( char_buf, '\0', buf_size);
  rite_fgets(rfp, (unsigned char*)char_buf, (offset - (MRB_DUMP_SIZE_OF_SHORT * RITE_FILE_HEX_SIZE)), TRUE); //class or module name
  hex_to_str(char_buf, (char*)(dst + MRB_DUMP_SIZE_OF_SHORT + MRB_DUMP_SIZE_OF_SHORT), &clen); //class or module name
  dst += uint16_to_bin((MRB_DUMP_SIZE_OF_SHORT/*crc*/ + clen), (char*)dst); //offset of isec block
  dst += hex_to_bin16(dst, hcrc);                 //header CRC
  dst += clen;

  //ISEQ BLOCK
  rite_fgets(rfp, hex8, sizeof(hex8), TRUE);            //iseq length
  dst += hex_to_bin32(dst, hex8);
  blocklen = hex_to_uint32(hex8);
  for (i=0; i<blocklen; i++) {
    rite_fgets(rfp, hex8, sizeof(hex8), TRUE);          //iseq
    dst += hex_to_bin32(dst, hex8);
  }
  rite_fgets(rfp, hcrc, sizeof(hcrc), TRUE);            //iseq CRC
  dst += hex_to_bin16(dst, hcrc);

  //POOL BLOCK
  rite_fgets(rfp, hex8, sizeof(hex8), TRUE);            //pool length
  dst += hex_to_bin32(dst, hex8);
  blocklen = hex_to_uint32(hex8);
  for (i=0; i<blocklen; i++) {
    rite_fgets(rfp, hex2, sizeof(hex2), TRUE);          //TT
    dst += hex_to_bin8(dst, hex2);
    rite_fgets(rfp, hex4, sizeof(hex4), TRUE);          //pool data length
    pdl = hex_to_uint16(hex4);

    if ( pdl > buf_size - 1) {
      buf_size = pdl + 1;
      if ((char_buf = (char *)mrb_realloc(mrb, char_buf, buf_size)) == NULL)
        goto error_exit;
    }
    memset(char_buf, '\0', buf_size);
    rite_fgets(rfp, (unsigned char*)char_buf, pdl, FALSE); //pool
    hex_to_str(char_buf, (char*)(dst + MRB_DUMP_SIZE_OF_SHORT), &clen);
    dst += uint16_to_bin(clen, (char*)dst);
    dst += clen;
  }
  rite_fgets(rfp, hcrc, sizeof(hcrc), TRUE);            //pool CRC
  dst += hex_to_bin16(dst, hcrc);

  //SYMS BLOCK
  rite_fgets(rfp, hex8, sizeof(hex8), TRUE);            //syms length
  dst += hex_to_bin32(dst, hex8);
  blocklen = hex_to_uint32(hex8);
  for (i=0; i<blocklen; i++) {
    rite_fgets(rfp, hex4, sizeof(hex4), TRUE);          //symbol name length
    snl = hex_to_uint16(hex4);

    if (snl == MRB_DUMP_NULL_SYM_LEN) {
      dst += uint16_to_bin(snl, (char*)dst);
      continue;
    }

    if ( snl > buf_size - 1) {
      buf_size = snl + 1;
      if ((char_buf = (char *)mrb_realloc(mrb, char_buf, buf_size)) == NULL)
        goto error_exit;
    }
    memset(char_buf, '\0', buf_size);
    rite_fgets(rfp, (unsigned char*)char_buf, snl, FALSE); //symbol name
    hex_to_str(char_buf, (char*)(dst + MRB_DUMP_SIZE_OF_SHORT), &clen);
    dst += uint16_to_bin(clen, (char*)dst);
    dst += clen;
  }
  rite_fgets(rfp, hcrc, sizeof(hcrc), TRUE);            //syms CRC
  dst += hex_to_bin16(dst, hcrc);

  *len = dst - pStart;

error_exit:
  if (char_buf)
    mrb_free(mrb, char_buf);

  return MRB_DUMP_OK;
}
Beispiel #8
0
int main(int argc, char **argv) {
  int err, option_index, c, clientlen, counter;
  unsigned char rcv_plaintext[AES_BLOCK_SIZE];
  unsigned char rcv_ciphertext[AES_BLOCK_SIZE];
  unsigned char send_plaintext[AES_BLOCK_SIZE];
  unsigned char send_ciphertext[AES_BLOCK_SIZE];
  aes_context enc_ctx, dec_ctx;
  in_addr_t ip_addr;
  struct sockaddr_in server_addr;
  FILE *c_file, *d_file, *m_file;
  ssize_t read_size, write_size;
  struct sockaddr_in client_addr;
  tls_msg err_msg, send_msg, rcv_msg;
  mpz_t client_exp, client_mod;
  fd_set readfds;
  struct timeval tv;

  c_file = d_file = m_file = NULL;

  mpz_init(client_exp);
  mpz_init(client_mod);

  /*
   * This section is networking code that you don't need to worry about.
   * Look further down in the function for your part.
   */

  memset(&ip_addr, 0, sizeof(in_addr_t));

  option_index = 0;
  err = 0;

  static struct option long_options[] = {
    {"ip", required_argument, 0, 'i'},
    {"cert", required_argument, 0, 'c'},
    {"exponent", required_argument, 0, 'd'},
    {"modulus", required_argument, 0, 'm'},
    {0, 0, 0, 0},
  };

  while (1) {
    c = getopt_long(argc, argv, "c:i:d:m:", long_options, &option_index);
    if (c < 0) {
      break;
    }
    switch(c) {
    case 0:
      usage();
      break;
    case 'c':
      c_file = fopen(optarg, "r");
      if (c_file == NULL) {
	perror("Certificate file error");
	exit(1);
      }
      break;
    case 'd':
      d_file = fopen(optarg, "r");
      if (d_file == NULL) {
	perror("Exponent file error");
	exit(1);
      }
      break;
    case 'i':
      ip_addr = inet_addr(optarg);
      break;
    case 'm':
      m_file = fopen(optarg, "r");
      if (m_file == NULL) {
	perror("Modulus file error");
	exit(1);
      }
      break;
    case '?':
      usage();
      break;
    default:
      usage();
      break;
    }
  }

  if (d_file == NULL || c_file == NULL || m_file == NULL) {
    usage();
  }
  if (argc != 9) {
    usage();
  }

  mpz_inp_str(client_exp, d_file, 0);
  mpz_inp_str(client_mod, m_file, 0);

  signal(SIGTERM, kill_handler);

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0) {
    perror("Could not open socket");
    exit(1);
  }

  memset(&server_addr, 0, sizeof(struct sockaddr_in));
  server_addr.sin_family = AF_INET;
  server_addr.sin_addr.s_addr = ip_addr;
  server_addr.sin_port = htons(HANDSHAKE_PORT);
  err = connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
  if (err < 0) {
    perror("Could not bind socket");
    cleanup();
  }

  // YOUR CODE HERE
  // IMPLEMENT THE TLS HANDSHAKE


  // send client hello
  hello_message client_hello_msg = {CLIENT_HELLO, random_int(), TLS_RSA_WITH_AES_128_ECB_SHA256};
  err = send_tls_message(sockfd, &client_hello_msg, HELLO_MSG_SIZE);
  if (err == ERR_FAILURE) {
    exit(1);
  }


  // receive server hello
  hello_message server_hello_msg;
  err = receive_tls_message(sockfd, &server_hello_msg, HELLO_MSG_SIZE, SERVER_HELLO);
  if (err == ERR_FAILURE) {
    exit(1);
  }

  // send client certificate
  cert_message client_cert_msg;
  client_cert_msg.type = CLIENT_CERTIFICATE;
  fgets(client_cert_msg.cert, RSA_MAX_LEN, c_file);
  err = send_tls_message(sockfd, &client_cert_msg, CERT_MSG_SIZE);
  if (err == ERR_FAILURE) {
    exit(1);
  }

  //receive server certificate

  cert_message server_cert_msg;

  err = receive_tls_message(sockfd, &server_cert_msg, CERT_MSG_SIZE, SERVER_CERTIFICATE);
  if (err == ERR_FAILURE) {
    exit(1);
  }

  mpz_t cert_plaintext;
  mpz_init(cert_plaintext);

  mpz_t ca_key_exp;
  mpz_init(ca_key_exp);

  mpz_t ca_key_mod;
  mpz_init(ca_key_mod);

  mpz_set_str(ca_key_exp, CA_EXPONENT, 0);
  mpz_set_str(ca_key_mod, CA_MODULUS, 0);

  decrypt_cert(cert_plaintext, &server_cert_msg, ca_key_exp, ca_key_mod);

  char cert_plaintext_string[RSA_MAX_LEN];
  mpz_get_ascii(cert_plaintext_string, cert_plaintext);


  mpz_t exponentNum;
  mpz_init(exponentNum);
  mpz_t modNum;
  mpz_init(modNum);
  get_cert_exponent(exponentNum, cert_plaintext_string);
  get_cert_modulus(modNum, cert_plaintext_string);


  mpz_t premaster_secret_int;
  mpz_init(premaster_secret_int);
  
  int p_secret_int = random_int();
  mpz_t p_secret;
  mpz_init(p_secret);
  mpz_add_ui(p_secret, p_secret, p_secret_int);

  perform_rsa(premaster_secret_int, p_secret, exponentNum, modNum);

  ps_msg premaster_secret;
  premaster_secret.type = PREMASTER_SECRET;
  mpz_get_str(premaster_secret.ps, 16, premaster_secret_int);


  // send premaster secret
  err = send_tls_message(sockfd, &premaster_secret, PS_MSG_SIZE);
  if (err == ERR_FAILURE) {
    exit(1);
  }

 
  ps_msg master_secret;

  // receive master secret
  err = receive_tls_message(sockfd, &master_secret, PS_MSG_SIZE, VERIFY_MASTER_SECRET);
  if (err == ERR_FAILURE) {
    exit(1);
  }


  mpz_t decrypted_master_secret;
  mpz_init(decrypted_master_secret);

  mpz_t key_exp;
  mpz_init(key_exp);

  mpz_t key_mod;
  mpz_init(key_mod);

  

  fseek (d_file, 0, SEEK_END);
  long length = ftell (d_file);
  fseek (d_file, 0, SEEK_SET);

  char private_key[length];
  fgets(private_key, length, d_file);
  mpz_set_str(key_exp, private_key, 0);

  fseek (m_file, 0, SEEK_END);
  length = ftell (m_file);
  fseek (m_file, 0, SEEK_SET);

  char modulus[length];
  fgets(modulus, length, m_file);
  mpz_set_str(key_mod, modulus, 0);


  decrypt_verify_master_secret(decrypted_master_secret, &master_secret, key_exp, key_mod);

  char decrypted_master_secret_char[16];

  mpz_get_str(decrypted_master_secret_char, 16, decrypted_master_secret);

  unsigned char computed_master_secret[16];

  compute_master_secret(p_secret_int, client_hello_msg.random, server_hello_msg.random, computed_master_secret);

  
  if (strcasecmp(decrypted_master_secret_char, hex_to_str(computed_master_secret, 16)) == 0) {
    printf("Begin messages.\n");
  } 

  /*
   * START ENCRYPTED MESSAGES
   */

  memset(send_plaintext, 0, AES_BLOCK_SIZE);
  memset(send_ciphertext, 0, AES_BLOCK_SIZE);
  memset(rcv_plaintext, 0, AES_BLOCK_SIZE);
  memset(rcv_ciphertext, 0, AES_BLOCK_SIZE);

  memset(&rcv_msg, 0, TLS_MSG_SIZE);

  aes_init(&enc_ctx);
  aes_init(&dec_ctx);
  
  // YOUR CODE HERE
  // SET AES KEYS

  if (aes_setkey_enc (&enc_ctx, computed_master_secret, 128)){
    printf("setting key didn't work n***a\n");
  }

  if (aes_setkey_dec (&dec_ctx, computed_master_secret, 128)){
    printf("setting key didn't work n***a\n");
  }

  fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK);
  /* Send and receive data. */
  while (1) {
    FD_ZERO(&readfds);
    FD_SET(STDIN_FILENO, &readfds);
    FD_SET(sockfd, &readfds);
    tv.tv_sec = 2;
    tv.tv_usec = 10;

    select(sockfd+1, &readfds, NULL, NULL, &tv);
    if (FD_ISSET(STDIN_FILENO, &readfds)) {
      counter = 0;
      memset(&send_msg, 0, TLS_MSG_SIZE);
      send_msg.type = ENCRYPTED_MESSAGE;
      memset(send_plaintext, 0, AES_BLOCK_SIZE);
      read_size = read(STDIN_FILENO, send_plaintext, AES_BLOCK_SIZE);
      while (read_size > 0 && counter + AES_BLOCK_SIZE < TLS_MSG_SIZE - INT_SIZE) {
	if (read_size > 0) {
	  err = aes_crypt_ecb(&enc_ctx, AES_ENCRYPT, send_plaintext, send_ciphertext);
	  memcpy(send_msg.msg + counter, send_ciphertext, AES_BLOCK_SIZE);
	  counter += AES_BLOCK_SIZE;
	}
	memset(send_plaintext, 0, AES_BLOCK_SIZE);
	read_size = read(STDIN_FILENO, send_plaintext, AES_BLOCK_SIZE);
      }
      write_size = write(sockfd, &send_msg, INT_SIZE+counter+AES_BLOCK_SIZE);
      if (write_size < 0) {
	perror("Could not write to socket");
	cleanup();
      }
    } else if (FD_ISSET(sockfd, &readfds)) {
      memset(&rcv_msg, 0, TLS_MSG_SIZE);
      memset(rcv_ciphertext, 0, AES_BLOCK_SIZE);
      read_size = read(sockfd, &rcv_msg, TLS_MSG_SIZE);
      if (read_size > 0) {
	if (rcv_msg.type != ENCRYPTED_MESSAGE) {
	  goto out;
	}
	memcpy(rcv_ciphertext, rcv_msg.msg, AES_BLOCK_SIZE);
	counter = 0;
	while (counter < read_size - INT_SIZE - AES_BLOCK_SIZE) {
	  aes_crypt_ecb(&dec_ctx, AES_DECRYPT, rcv_ciphertext, rcv_plaintext);
	  printf("%s", rcv_plaintext);
	  counter += AES_BLOCK_SIZE;
	  memcpy(rcv_ciphertext, rcv_msg.msg+counter, AES_BLOCK_SIZE);
	}
	printf("\n");
      }
    }

  }

 out:
  close(sockfd);
  return 0;
}
Beispiel #9
0
void Tox_Dispatcher::friend_request(Tox *, const uint8_t *public_key,
    const uint8_t *, size_t , void *)
{
    LOG(INFO) << "Friend request received from: "
        << hex_to_str(public_key, TOX_PUBLIC_KEY_SIZE);
}
int main(int argc, char **argv) {
	int err, option_index, c, clientlen, counter;
	unsigned char rcv_plaintext[AES_BLOCK_SIZE];
	unsigned char rcv_ciphertext[AES_BLOCK_SIZE];
	unsigned char send_plaintext[AES_BLOCK_SIZE];
	unsigned char send_ciphertext[AES_BLOCK_SIZE];
	aes_context enc_ctx, dec_ctx;
	in_addr_t ip_addr;
	struct sockaddr_in server_addr;
	FILE *c_file, *d_file, *m_file;
	ssize_t read_size, write_size;
	struct sockaddr_in client_addr;
	tls_msg err_msg, send_msg, rcv_msg;
	mpz_t client_exp, client_mod;
	fd_set readfds;
	struct timeval tv;

	c_file = d_file = m_file = NULL;

	mpz_init(client_exp);
	mpz_init(client_mod);


	/*
	 * This section is networking code that you don't need to worry about.
	 * Look further down in the function for your part.
	 */

	memset(&ip_addr, 0, sizeof(in_addr_t));

	option_index = 0;
	err = 0;

	static struct option long_options[] = {
		{"ip", required_argument, 0, 'i'},
		{"cert", required_argument, 0, 'c'},
		{"exponent", required_argument, 0, 'd'},
		{"modulus", required_argument, 0, 'm'},
		{0, 0, 0, 0},
	};

	while (1) {
		c = getopt_long(argc, argv, "c:i:d:m:", long_options, &option_index);
		if (c < 0) {
			break;
		}
		switch(c) {
		case 0:
			usage();
			break;
		case 'c':
			c_file = fopen(optarg, "r");
			if (c_file == NULL) {
				perror("Certificate file error");
				exit(1);
			}
			break;
		case 'd':
			d_file = fopen(optarg, "r");
			if (d_file == NULL) {
				perror("Exponent file error");
				exit(1);
			}
			break;
		case 'i':
			ip_addr = inet_addr(optarg);
			break;
		case 'm':
			m_file = fopen(optarg, "r");
			if (m_file == NULL) {
				perror("Modulus file error");
				exit(1);
			}
			break;
		case '?':
			usage();
			break;
		default:
			usage();
			break;
		}
	}

	if (d_file == NULL || c_file == NULL || m_file == NULL) {
		usage();
	}
	if (argc != 9) {
		usage();
	}

	mpz_inp_str(client_exp, d_file, 0);
	mpz_inp_str(client_mod, m_file, 0);

	signal(SIGTERM, kill_handler);

	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if (sockfd < 0) {
		perror("Could not open socket");
		exit(1);
	}


	memset(&server_addr, 0, sizeof(struct sockaddr_in));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = ip_addr;
	server_addr.sin_port = htons(HANDSHAKE_PORT);
	err = connect(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
	if (err < 0) {
		perror("Could not bind socket");
		cleanup();
	}

	// YOUR CODE HERE
	// IMPLEMENT THE TLS HANDSHAKE
	int send_message_int, receive_messge_int;
	/* error handling (To be continued) */
	// ********************************************************************
	// ********************************************************************
	// ********************************************************************
	
	// Whenever send or receive, need to check this feedback
	int feedback;
	//  =============== [Send] Client Hello =======================
	hello_message client_hello_message;
	int client_random;
	int server_random;
	memset(&client_hello_message, 0, sizeof(hello_message));

	client_random = random_int();
	printf("client_random: %d\n", client_random);
	client_hello_message.type = CLIENT_HELLO;
	client_hello_message.random = client_random;
	client_hello_message.cipher_suite = TLS_RSA_WITH_AES_128_ECB_SHA256;
	feedback = send_tls_message(sockfd, &client_hello_message, sizeof(hello_message));
	if (feedback != ERR_OK){
		perror("[CLIENT_HELLO]: can't send tls message");
		cleanup();	
	}

	//  =============== [Receive] Sever Hello =======================
	hello_message server_hello_message;
	memset(&server_hello_message, 0, sizeof(hello_message));
	feedback = receive_tls_message(sockfd, &server_hello_message, sizeof(hello_message), SERVER_HELLO);
	if (feedback != ERR_OK){
		perror("[SERVER_HELLO]: can't receive tls message");
		cleanup();		
	}
	server_random = server_hello_message.random;
	printf("server_random: %d\n", server_random);

	//  =============== [Send] Client Certificate ================
	mpz_t client_certificate_mpz;
	cert_message client_certificate;
	int byte_read;
	mpz_init(client_certificate_mpz);
	// May need to verify whether we connect to the correct server(i.e.torus.ce.berkeley.edu).
	memset(&client_certificate, 0, sizeof(cert_message));
	client_certificate.type = CLIENT_CERTIFICATE;
	fread(client_certificate.cert, RSA_MAX_LEN, 1, c_file);
	//printf("Client Certificate: %s\n", client_certificate.cert);
	feedback = send_tls_message(sockfd, &client_certificate, CERT_MSG_SIZE);
	if (feedback != ERR_OK){
		perror("[CLIENT CERTIFICATE]: can't send tls message");
		cleanup();
	}

	//  =============== [Receive] Server Certificate ================
	cert_message server_certificate;
	mpz_t decrypted_sever_cert_mpz;
	mpz_t ca_exponent;
	mpz_t ca_modulus;
	mpz_t server_public_key_exponent;
	mpz_t server_public_key_modulus;
	char decrypted_server_cert [RSA_MAX_LEN];

	memset(&server_certificate, 0, sizeof(cert_message));
	mpz_init(decrypted_sever_cert_mpz);
	mpz_init(ca_exponent);
	mpz_init(ca_modulus);
	mpz_init(server_public_key_exponent);
	mpz_init(server_public_key_modulus);
	memset(decrypted_server_cert, 0, RSA_MAX_LEN);

	feedback = receive_tls_message(sockfd, &server_certificate, sizeof(cert_message), SERVER_CERTIFICATE);
	if (feedback != ERR_OK){
		perror("[SERVER CERTIFICATE]: can't receive tls message");
		cleanup();
	}
	// May need to verify whether we connect to the correct server(i.e.torus.ce.berkeley.edu).
	// Decrypt Server Certificate
	mpz_set_str(ca_exponent, CA_EXPONENT, 0);
	mpz_set_str(ca_modulus, CA_MODULUS, 0);
	decrypt_cert(decrypted_sever_cert_mpz, &server_certificate, ca_exponent, ca_modulus);
	mpz_get_ascii(decrypted_server_cert, decrypted_sever_cert_mpz);                       // Convert mpz to char array
	//printf("decrypted_server_cert: %s\n", decrypted_server_cert);
	get_cert_exponent(server_public_key_exponent, decrypted_server_cert);
	get_cert_modulus(server_public_key_modulus, decrypted_server_cert);


	//  =============== [Send] E_server_public_key (Premaster Secret) ================
	// Construct encrypted(premaster secret)
	mpz_t premaster_secret_encrypted, premaster_secret_mpz;
	int premaster_secret;
	char premaster[16];
	ps_msg encrypted_ps_message;
	mpz_init(premaster_secret_encrypted);
	mpz_init(premaster_secret_mpz);	
	memset(&encrypted_ps_message, 0, sizeof(ps_msg));
	
	// Generate and Covert Premaster Secret to mpz
	sleep(3);
	premaster_secret = random_int();
	printf("premaster_secret: %d\n", premaster_secret);
	sprintf(premaster, "%d", premaster_secret);
	mpz_set_str(premaster_secret_mpz, premaster, 10);
	// perform_rsa(premaster_secret_encrypted, premaster_secret_mpz, server_public_key_exponent, server_public_key_modulus);
	// ps_msg *encrypted_ps_message;
	// encrypted_ps_message = (ps_msg*) malloc(sizeof(ps_msg));
	// encrypted_ps_message->type = PREMASTER_SECRET;
	// mpz_get_ascii(encrypted_ps_message->ps, premaster_secret_encrypted);
	// send_tls_message(sockfd, encrypted_ps_message, sizeof(ps_msg));
	// ps_msg encrypted_server_ms_message;
	// memset(&encrypted_server_ms_message, 0, sizeof(ps_msg));
	// receive_messge_int = receive_tls_message(sockfd, &encrypted_server_ms_message, sizeof(ps_msg), PREMASTER_SECRET);
	// if (receive_messge_int == ERR_FAILURE) {
	// 	perror("Could not get the master secret");
	// 	cleanup();
	// }
	// gmp_printf("premaster_secret_mpz: %Zd\n", premaster_secret_mpz);
	// gmp_printf("server_public_key_exponent: %Zx\n", server_public_key_exponent);
	// gmp_printf("server_public_key_modulus: %Zx\n", server_public_key_modulus);
	perform_rsa(premaster_secret_encrypted, premaster_secret_mpz, server_public_key_exponent, server_public_key_modulus);
	encrypted_ps_message.type = PREMASTER_SECRET;
	mpz_get_str(encrypted_ps_message.ps, 16, premaster_secret_encrypted);
	feedback = send_tls_message(sockfd, &encrypted_ps_message, sizeof(ps_msg));
	if (feedback != ERR_OK) {
		perror("[E_server_public_key (Premaster secret)]: can't send tls message");
		cleanup();
	}
	
	//  =============== [Receive] E_client_public_key (Master Secret) ================
	ps_msg encrypted_server_ms_message;
	mpz_t decrypted_ms;
	mpz_t master_secret_mpz;
	unsigned long long master_secret_long;
	unsigned char master_secret[SHA_BLOCK_SIZE];
	int result;
	memset(&encrypted_server_ms_message, 0, sizeof(ps_msg));
	mpz_init(decrypted_ms);
	memset(master_secret, 0, SHA_BLOCK_SIZE);
	mpz_init(master_secret_mpz);
	feedback = receive_tls_message(sockfd, &encrypted_server_ms_message, sizeof(ps_msg), VERIFY_MASTER_SECRET);
	if (feedback != ERR_OK) {
		perror("[E_client_public_key (master secret)]: can't receive tls message");
		cleanup();
	}

	decrypt_verify_master_secret(decrypted_ms, &encrypted_server_ms_message, client_exp, client_mod);
	compute_master_secret(premaster_secret, client_random, server_random, master_secret);
	char* master_secret_str = hex_to_str(master_secret, SHA_BLOCK_SIZE);
	mpz_set_str(master_secret_mpz, master_secret_str, 16);
	result = mpz_cmp(master_secret_mpz, decrypted_ms);
	printf("%d", result);
	if (result != 0) {
		perror("Decrypted server master secret doesn't match computed master secret!");
		cleanup();
	}
	if (client_random != premaster_secret && server_random != premaster_secret){
		//printf("1\n");
	}else{
		//printf("0\n");
	}
	//printf("result: %d\n", result);
	free(master_secret_str);
	close(sockfd);
	mpz_clear(client_exp);
	mpz_clear(client_mod);
	mpz_clear(client_certificate_mpz);
	mpz_clear(decrypted_sever_cert_mpz);
	mpz_clear(ca_exponent);
	mpz_clear(ca_modulus);
	mpz_clear(premaster_secret_encrypted);
	mpz_clear(server_public_key_exponent);
	mpz_clear(server_public_key_modulus);
	mpz_clear(premaster_secret_mpz);
	mpz_clear(decrypted_ms);
	mpz_clear(master_secret_mpz);
	cleanup();
	return 0;
}
Beispiel #11
0
int gdb_thread_packet(struct connection *connection, char *packet, int packet_size)
{
	struct target *target = get_target_from_connection(connection);

	if (strstr(packet, "qThreadExtraInfo,"))
	{
		if ((target->rtos != NULL) && (target->rtos->thread_details != NULL) && (target->rtos->thread_count != 0))
		{
			threadid_t threadid = 0;
			int found = -1;
			sscanf(packet, "qThreadExtraInfo,%" SCNx64, &threadid );

			if ((target->rtos != NULL) && (target->rtos->thread_details
					!= NULL)) {
				int thread_num;
				for (thread_num = 0; thread_num
						< target->rtos->thread_count; thread_num++) {
					if (target->rtos->thread_details[thread_num].threadid
							== threadid) {
						if (target->rtos->thread_details[thread_num].exists) {
							found = thread_num;
						}
					}
				}
			}
			if (found == -1) {
				gdb_put_packet(connection, "E01", 3); // thread not found
				return ERROR_OK;
			}

			struct thread_detail* detail = &target->rtos->thread_details[found];

			int str_size = 0;
			if ( detail->display_str != NULL )
			{
				str_size += strlen(detail->display_str);
			}
			if ( detail->thread_name_str != NULL )
			{
				str_size += strlen(detail->thread_name_str);
			}
			if ( detail->extra_info_str != NULL )
			{
				str_size += strlen(detail->extra_info_str);
			}

			char * tmp_str = (char*) malloc( str_size + 7 );
			char*  tmp_str_ptr = tmp_str;

			if ( detail->display_str != NULL )
			{
				tmp_str_ptr += sprintf( tmp_str_ptr, "%s", detail->display_str );
			}
			if ( detail->thread_name_str != NULL )
			{
				if ( tmp_str_ptr != tmp_str )
				{
					tmp_str_ptr += sprintf( tmp_str_ptr, " : " );
				}
				tmp_str_ptr += sprintf( tmp_str_ptr, "%s", detail->thread_name_str );
			}
			if ( detail->extra_info_str != NULL )
			{
				if ( tmp_str_ptr != tmp_str )
				{
					tmp_str_ptr += sprintf( tmp_str_ptr, " : " );
				}
				tmp_str_ptr += sprintf( tmp_str_ptr, " : %s", detail->extra_info_str );
			}

			assert(strlen(tmp_str) ==
				(size_t) (tmp_str_ptr - tmp_str));

			char * hex_str = (char*) malloc( strlen(tmp_str)*2 +1 );
			str_to_hex( hex_str, tmp_str );

			gdb_put_packet(connection, hex_str, strlen(hex_str));
			free(hex_str);
			free(tmp_str);
			return ERROR_OK;

		}
		gdb_put_packet(connection, "", 0);
		return ERROR_OK;
	}
	else if (strstr(packet, "qSymbol"))
	{
		if ( target->rtos != NULL )
		{
			int next_symbol_num = -1;
			if (target->rtos->symbols == NULL)
			{
				target->rtos->type->get_symbol_list_to_lookup( &target->rtos->symbols );
			}
			if (0 == strcmp( "qSymbol::", packet ) )
			{
				// first query -
				next_symbol_num = 0;
			}
			else
			{
				int64_t value = 0;
				char * hex_name_str = malloc( strlen(packet));
				char * name_str;
				int symbol_num;

				char* found = strstr( packet, "qSymbol::" );
				if (0 == found )
				{
					sscanf(packet, "qSymbol:%" SCNx64 ":%s", &value, hex_name_str);
				}
				else
				{
					// No value returned by GDB - symbol was not found
					sscanf(packet, "qSymbol::%s", hex_name_str);
				}
				name_str = (char*) malloc( 1+ strlen(hex_name_str) / 2 );

				hex_to_str( name_str, hex_name_str );


				symbol_num = 0;
				while ( ( target->rtos->symbols[ symbol_num ].symbol_name != NULL ) && ( 0 != strcmp( target->rtos->symbols[ symbol_num ].symbol_name, name_str ) ) )
				{
					symbol_num++;
				}


				if ( target->rtos->symbols[ symbol_num ].symbol_name == NULL )
				{
					LOG_OUTPUT("ERROR: unknown symbol\r\n");
					gdb_put_packet(connection, "OK", 2);
					return ERROR_OK;
				}

				target->rtos->symbols[ symbol_num ].address = value;

				next_symbol_num = symbol_num+1;
				free( hex_name_str );
				free( name_str );

			}

			int symbols_done = 0;
			if ( target->rtos->symbols[ next_symbol_num ].symbol_name == NULL )
			{
				if ( ( target->rtos_auto_detect == false ) ||
					 ( 1 == target->rtos->type->detect_rtos( target ) ) )
				{
					// Found correct RTOS or not autodetecting
					if ( target->rtos_auto_detect == true )
					{
						LOG_OUTPUT( "Auto-detected RTOS: %s\r\n",target->rtos->type->name );
					}
					symbols_done = 1;
				}
				else
				{
					// Auto detecting RTOS and currently not found
					if( 1 != rtos_try_next( target ) )
					{
						// No more RTOS's to try
						symbols_done = 1;
					}
					else
					{
						next_symbol_num = 0;
						target->rtos->type->get_symbol_list_to_lookup( &target->rtos->symbols );
					}

				}
			}


			if ( symbols_done == 1 )
			{
				target->rtos_auto_detect = false;
				target->rtos->type->create( target );
				target->rtos->type->update_threads(target->rtos);
				// No more symbols needed
				gdb_put_packet(connection, "OK", 2);
				return ERROR_OK;

			}
			else
			{
				char* symname = target->rtos->symbols[ next_symbol_num ].symbol_name;
				char qsymstr[] = "qSymbol:";
				char * opstring = (char*)malloc(sizeof(qsymstr)+strlen(symname)*2+1);
				char * posptr = opstring;
				posptr += sprintf( posptr, "%s", qsymstr );
				str_to_hex( posptr, symname );
				gdb_put_packet(connection, opstring, strlen(opstring));
				free(opstring);
				return ERROR_OK;
			}

		}
		gdb_put_packet(connection, "OK", 2);
		return ERROR_OK;
	}
	else if (strstr(packet, "qfThreadInfo"))
	{
		int i;
		if ( ( target->rtos != NULL ) && ( target->rtos->thread_count != 0 ) )
		{

			char* out_str = (char*) malloc(17 * target->rtos->thread_count + 5);
			char* tmp_str = out_str;
			tmp_str += sprintf(tmp_str, "m");
			for (i = 0; i < target->rtos->thread_count; i++) {
				if (i != 0) {
					tmp_str += sprintf(tmp_str, ",");
				}
				tmp_str += sprintf(tmp_str, "%016" PRIx64,
						target->rtos->thread_details[i].threadid);
			}
			tmp_str[0] = 0;
			gdb_put_packet(connection, out_str, strlen(out_str));
		}
		else
		{
			gdb_put_packet(connection, "", 0);
		}

		return ERROR_OK;
	}
	else if (strstr(packet, "qsThreadInfo"))
	{
		gdb_put_packet(connection, "l", 1);
		return ERROR_OK;
	}
	else if (strstr(packet, "qAttached"))
	{
		gdb_put_packet(connection, "1", 1);
		return ERROR_OK;
	}
	else if (strstr(packet, "qOffsets"))
	{
		char offsets[] = "Text=0;Data=0;Bss=0";
		gdb_put_packet(connection, offsets, sizeof(offsets)-1);
		return ERROR_OK;
	}
	else if (strstr(packet, "qC"))
	{
		if( target->rtos!=NULL )
		{
			char buffer[15];
			int size;
			size = snprintf(buffer, 15, "QC%08X", (int)target->rtos->current_thread);
			gdb_put_packet(connection, buffer, size);
		}
		else
		{
			gdb_put_packet(connection, "QC0", 3);
		}
		return ERROR_OK;
	}
	else if ( packet[0] == 'T' ) // Is thread alive?
	{
		threadid_t threadid;
		int found = -1;
		sscanf(packet, "T%" SCNx64, &threadid);
		if ((target->rtos != NULL) && (target->rtos->thread_details
				!= NULL)) {
			int thread_num;
			for (thread_num = 0; thread_num
					< target->rtos->thread_count; thread_num++) {
				if (target->rtos->thread_details[thread_num].threadid
						== threadid) {
					if (target->rtos->thread_details[thread_num].exists) {
						found = thread_num;
					}
				}
			}
		}
		if (found != -1) {
			gdb_put_packet(connection, "OK", 2); // thread alive
		} else {
			gdb_put_packet(connection, "E01", 3); // thread not found
		}
		return ERROR_OK;
	}
	else if ( packet[0] == 'H') // Set current thread ( 'c' for step and continue, 'g' for all other operations )
	{
		if (packet[1] == 'g')
		{
			sscanf(packet, "Hg%16" SCNx64, &current_threadid);
		}
		gdb_put_packet(connection, "OK", 2);
		return ERROR_OK;
	}

	return GDB_THREAD_PACKET_NOT_CONSUMED;
}
Beispiel #12
0
    int ObRange::to_string(char* buffer, const int32_t length) const
    {
      int ret = OB_SUCCESS;
      if (NULL == buffer || length <= 0) 
      {
        ret = OB_INVALID_ARGUMENT;
      }

      int32_t key_length = 0;
      int32_t pos = 0;
      int32_t remain_length = 0;
      int32_t byte_len = 0;
      int32_t max_key_length = 0;

      // calc print key length;
      if (border_flag_.is_min_value() && border_flag_.is_max_value())
      {
        key_length += 6; // MIN, MAX
      }
      else if (border_flag_.is_min_value())
      {
        key_length += 3 + 2 * end_key_.length(); // MIN, XXX
      }
      else if (border_flag_.is_max_value())
      {
        key_length += 3 + 2 * start_key_.length(); // XXX, MAX
      }
      else
      {
        key_length += 2 * end_key_.length() + 2 * start_key_.length(); // XXX, MAX
      }

      key_length += 3; // (,)

      // print table:xxx
      if (OB_SUCCESS == ret)
      {
        pos = snprintf(buffer, length, "table:%ld, ", table_id_);
        if (pos >= length)
        {
          ret = OB_SIZE_OVERFLOW;
        }
        else
        {
          remain_length = length - pos;
        }
      }

      if (OB_SUCCESS == ret)
      {

        const char* lb = 0;
        if (border_flag_.inclusive_start()) lb = "[";
        else lb = "(";
        if (border_flag_.is_min_value()) lb = "(MIN";

        byte_len = snprintf(buffer + pos, remain_length, "%s", lb);
        pos += byte_len;
        remain_length = length - pos;

        // add start_key_
        if (!border_flag_.is_min_value())
        {
          // buffer not enough, store part of start key, start= "key"|".."|",]\0"
          max_key_length = (remain_length < key_length) ? ((remain_length - 3) / 2 - 2) / 2 : start_key_.length();
          byte_len = hex_to_str(start_key_.ptr(), max_key_length, buffer + pos, remain_length);
          pos += byte_len * 2;
          if (remain_length < key_length)
          {
            buffer[pos++] = '.';
            buffer[pos++] = '.';
          }
        }

        // add ,
        buffer[pos++] = ',';
        remain_length = length - pos;

        // add end_key_
        if (!border_flag_.is_max_value())
        {
          // buffer not enough, store part of end key, end key = "key"|".."|"]\0"
          max_key_length = (remain_length < end_key_.length() * 2 + 2) ? (remain_length - 4) / 2 : end_key_.length();
          int byte_len = hex_to_str(end_key_.ptr(), max_key_length, buffer + pos, remain_length);
          pos += byte_len * 2;
          if (remain_length < end_key_.length() * 2 + 2)
          {
            buffer[pos++] = '.';
            buffer[pos++] = '.';
          }
        }

        const char* rb = 0;
        if (border_flag_.inclusive_end()) rb = "]";
        else rb = ")";
        if (border_flag_.is_max_value()) rb = "MAX)";
        snprintf(buffer + pos, length - pos, "%s", rb);

      }

      return ret;
    }
Beispiel #13
0
  mpz_t random_mpz_enc;
  mpz_init(random_mpz);
  mpz_init(random_mpz_enc);
  mpz_set_ui(random_mpz, ps_int);
  perform_rsa(random_mpz_enc, random_mpz, public_exp, public_mod);

  char enc_ps_array[RSA_MAX_LEN];
  mpz_get_str(enc_ps_array, 16, random_mpz_enc); 
  strncpy((*ps_send).ps, enc_ps_array, RSA_MAX_LEN);
  send_tls_message(sockfd, ps_send, PS_MSG_SIZE);
  
  // Master Secret
  char master_secret[4 * sizeof(int)]; 
  char master_secret_str[4*sizeof(int)];
  compute_master_secret(ps_int, (*client_hello_send).random, (*server_hello_rcv).random, master_secret);
  memcpy(master_secret_str, hex_to_str(master_secret, sizeof(int)*4), sizeof(int)*4);

  // Compare Master Secrets
  ps_msg server_master[PS_MSG_SIZE];
  receive_tls_message(sockfd, server_master, PS_MSG_SIZE, VERIFY_MASTER_SECRET);

  mpz_t decrypted_master;
  mpz_init(decrypted_master);

  decrypt_verify_master_secret(decrypted_master, server_master, client_exp, client_mod);  

  char server_master_str[RSA_MAX_LEN];
  mpz_get_str(server_master_str, 16, decrypted_master);   

  int i = 0;
  while(master_secret_str[i]){