0

I have problems with trying to get this method to work, I am trying to use mbedtls with psk. Turns out the example they have is very hard to understand for a C novice like myself.

/*
 * Parse a string of pairs name1,key1[,name2,key2[,...]]
 * into a usable psk_entry list.
 *
 * Modifies the input string! This is not production quality!
 */

psk_entry * psk_parse( char * psk_string )
{
  psk_entry *cur = NULL, *new = NULL;
  char *p = psk_string;
  char *end = p;
  char *key_hex;

  while( *end != '\n' )
  {
    end++;
  }
  *end = ',';

  while( p <= end )
  {
    if( ( new = mbedtls_calloc( 1, sizeof( psk_entry ) ) ) == NULL )
      goto error;

    memset( new, 0, sizeof( psk_entry ) );

    GET_ITEM( new->name );
    GET_ITEM( key_hex );

    if( unhexify( new->key, key_hex, &new->key_len ) != 0 )
    {
      goto error;
    }

    new->next = cur;
    cur = new;
  }

  return( cur );

  error:
  psk_free( new );
  psk_free( cur );
  return( 0 );
}

What is the expecting string formatting to get this method to work? currently, I have

char * list = "JD,4f07d80fde6469fbdbf1f154a47f27c916dba68b644ff1ffa26295e598855810";

which gets passed to the method but I keep getting a segfault when *end = ',' is trying to get added.

cssko
  • 3,027
  • 1
  • 18
  • 21
  • 2
    `char * list = "JD..."` is a _read-only_ literal. Use `char list[] = "JD.."` – Paul Ogilvie Apr 01 '19 at 13:24
  • 2
    Also, the code is specifically looking for a newline character (`'\n'`) in the `psk_string` buffer, and will go past the end of the buffer while looking for it. That is another case of _undefined behavior_. – Ian Abbott Apr 01 '19 at 13:40
  • @IanAbbott I guess the code was modified from using `fgets`, but even there a newline might not always be present. – Weather Vane Apr 01 '19 at 13:42
  • @WeatherVane As the code comment says, "This is not production quality!" – Ian Abbott Apr 01 '19 at 13:43

0 Answers0