Exemplo n.º 1
0
static bool_t ortp_init_srtp_policy(srtp_t srtp, srtp_policy_t* policy, enum ortp_srtp_crypto_suite_t suite, ssrc_t ssrc, const char* b64_key)
{
	uint8_t* key;
	int key_size;
	err_status_t err;
	unsigned b64_key_length = strlen(b64_key);
		
	switch (suite) {
		case AES_128_SHA1_32:
			crypto_policy_set_aes_cm_128_hmac_sha1_32(&policy->rtp);
			// srtp doc says: not adapted to rtcp...
			crypto_policy_set_aes_cm_128_hmac_sha1_32(&policy->rtcp);
			break;
		case AES_128_NO_AUTH:
			crypto_policy_set_aes_cm_128_null_auth(&policy->rtp);
			// srtp doc says: not adapted to rtcp...
			crypto_policy_set_aes_cm_128_null_auth(&policy->rtcp);
			break;
		case NO_CIPHER_SHA1_80:
			crypto_policy_set_null_cipher_hmac_sha1_80(&policy->rtp);
			crypto_policy_set_null_cipher_hmac_sha1_80(&policy->rtcp);
			break;
		case AES_128_SHA1_80: /*default mode*/
		default:
			crypto_policy_set_rtp_default(&policy->rtp);
			crypto_policy_set_rtcp_default(&policy->rtcp);
	}
	//b64_decode(char const *src, size_t srcLen, void *dest, size_t destSize)
	key_size = b64_decode(b64_key, b64_key_length, 0, 0);
	if (key_size != policy->rtp.cipher_key_len) {
		ortp_error("Key size (%d) doesn't match the selected srtp profile (required %d)",
			key_size,
			policy->rtp.cipher_key_len);
			return FALSE;
	}
	key = (uint8_t*) ortp_malloc0(key_size+2); /*srtp uses padding*/
	if (b64_decode(b64_key, b64_key_length, key, key_size) != key_size) {
		ortp_error("Error decoding key");
		ortp_free(key);
		return FALSE;
	}
		
	policy->ssrc = ssrc;
	policy->key = key;
	policy->next = NULL;
		
	err = ortp_srtp_add_stream(srtp, policy);
	if (err != err_status_ok) {
		ortp_error("Failed to add incoming stream to srtp session (%d)", err);
		ortp_free(key);
		return FALSE;
	}
		
	ortp_free(key);
	return TRUE;
}
Exemplo n.º 2
0
int sec_read_msg(char *s, int level)
{
	int len;
	char *buf;
	int code;

	buf = malloc(strlen(s));
	len = b64_decode(s + 4, buf);	/* XXX */

	len = (*ftp->mech->decode) (ftp->app_data, buf, len, level);
	if (len < 0)
  {
    free(buf);
		return -1;
  }

	buf[len] = '\0';

	if (buf[3] == '-')
		code = 0;
	else
		sscanf(buf, "%d", &code);
	if (buf[len - 1] == '\n')
		buf[len - 1] = '\0';
	strcpy(s, buf);
	free(buf);
	return code;
}
Exemplo n.º 3
0
static int
parse_nat_msg(char *tbuf, char **ndx, int *t_size, fko_ctx_t ctx)
{
    if(  ctx->message_type == FKO_NAT_ACCESS_MSG
      || ctx->message_type == FKO_LOCAL_NAT_ACCESS_MSG
      || ctx->message_type == FKO_CLIENT_TIMEOUT_NAT_ACCESS_MSG
      || ctx->message_type == FKO_CLIENT_TIMEOUT_LOCAL_NAT_ACCESS_MSG)
    {
        if((*t_size = strcspn(*ndx, ":")) < 1)
            return(FKO_ERROR_INVALID_DATA_DECODE_NATACCESS_MISSING);

        if (*t_size > MAX_SPA_MESSAGE_SIZE)
            return(FKO_ERROR_INVALID_DATA_DECODE_NATACCESS_TOOBIG);

        strlcpy(tbuf, *ndx, *t_size+1);

        if(ctx->nat_access != NULL)
            free(ctx->nat_access);

        ctx->nat_access = calloc(1, *t_size+1); /* Yes, more than we need */
        if(ctx->nat_access == NULL)
            return(FKO_ERROR_MEMORY_ALLOCATION);

        if(b64_decode(tbuf, (unsigned char*)ctx->nat_access) < 0)
            return(FKO_ERROR_INVALID_DATA_DECODE_NATACCESS_DECODEFAIL);

        if(validate_nat_access_msg(ctx->nat_access) != FKO_SUCCESS)
            return(FKO_ERROR_INVALID_DATA_DECODE_NATACCESS_VALIDFAIL);

        *ndx += *t_size + 1;
    }

    return FKO_SUCCESS;
}
Exemplo n.º 4
0
static int
parse_username(char *tbuf, char **ndx, int *t_size, fko_ctx_t ctx)
{
    if((*t_size = strcspn(*ndx, ":")) < 1)
        return(FKO_ERROR_INVALID_DATA_DECODE_USERNAME_MISSING);

    if (*t_size > MAX_SPA_USERNAME_SIZE)
        return(FKO_ERROR_INVALID_DATA_DECODE_USERNAME_TOOBIG);

    strlcpy(tbuf, *ndx, *t_size+1);

    if(ctx->username != NULL)
        free(ctx->username);

    ctx->username = calloc(1, *t_size+1); /* Yes, more than we need */
    if(ctx->username == NULL)
        return(FKO_ERROR_MEMORY_ALLOCATION);

    if(b64_decode(tbuf, (unsigned char*)ctx->username) < 0)
        return(FKO_ERROR_INVALID_DATA_DECODE_USERNAME_DECODEFAIL);

    if(validate_username(ctx->username) != FKO_SUCCESS)
        return(FKO_ERROR_INVALID_DATA_DECODE_USERNAME_VALIDFAIL);

    *ndx += *t_size + 1;

    return FKO_SUCCESS;
}
Exemplo n.º 5
0
/*
 * Check basic authentication.  Return zero if authenticated.
 * Return -1 if failed authentication.
 * Return 1 if authentication not attempted.
 */
int basicauth_check (XML *xml, char *path, char *req)
{
  int i, n;
  char *uid, *pw;
  char buf[DBUFSZ];

  debug ("request: %s\n", req);
  					/* is basic auth required?	*/
  if ((n = xml_count (xml, path)) < 1)
    return (0);
					/* get authentication header	*/
  uid = strstr (req, "Authorization: Basic ");
  if (uid == NULL)
    return (1);
  uid += 21;				/* limit b64 decoding		*/
  if ((pw = strchr (uid, '\n')) != NULL)
    *pw = 0;
  b64_decode (buf, uid);
  if (pw != NULL)			/* restore if limited		*/
    *pw = '\n';
  uid = buf;
  if ((pw = strchr (uid, ':')) == NULL)
    return (1);
  *pw++ = 0;

  for (i = 0; i < n; i++)		/* check against users		*/
  {
    if ((strcmp (uid, xml_getf (xml, "%s%c%d%cUserID", 
      path, xml->indx_sep, i, xml->path_sep)) == 0) &&
     (strcmp (pw, xml_getf (xml, "%s%c%d%cPassword", 
      path, xml->indx_sep, i, xml->path_sep)) == 0)) 
      return (0);
  }
  return (-1);
}
Exemplo n.º 6
0
Arquivo: helpers.c Projeto: csm/arrow
int
read_link_file (const char *linkpath, uuid_t uuid)
{
  char uuidbuf[30];
  ssize_t len;
  char *p1, *p2;
  uint64_t hi, lo;

  len = readlink (linkpath, uuidbuf, sizeof(uuidbuf));
  if (len < 0)
	return -1;

  uuidbuf[len] = '\0';
  p1 = strchr (uuidbuf, '/');
  if (p1 == NULL)
	return -1;
  p1++;
  p2 = strchr (p1, '.');
  if (p2 == NULL)
	return -1;

  *p2 = '\0';
  p2++;

  /* I should just f*****g write a function that parses a base-64
     UUID. FIXME. 'n shit. */

  if (b64_decode (p1, &hi) != 0)
	{
/* 	  fprintf (stderr, "%s\n", uuidbuf); */
	  errno = EINVAL; /* FIXME we need a better error reporting mechanism. */
	  return -1;
	}
  if (b64_decode (p2, &lo) != 0)
	{
/* 	  fprintf (stderr, "%s\n", p); */
	  errno = EINVAL;
	  return -1;
	}

  uuid_from_longs (uuid, hi, lo);
  return 0;
}
Exemplo n.º 7
0
static int dec_add_fmtp(MSFilter *f, void *arg){
	DecData *d=(DecData*)f->data;
	const char *fmtp=(const char *)arg;
	char value[256];
	if (fmtp_get_value(fmtp,"sprop-parameter-sets",value,sizeof(value))){
		char * b64_sps=value;
		char * b64_pps=strchr(value,',');
		if (b64_pps){
			*b64_pps='\0';
			++b64_pps;
			ms_message("Got sprop-parameter-sets : sps=%s , pps=%s",b64_sps,b64_pps);
			d->sps=allocb(sizeof(value),0);
			d->sps->b_wptr+=b64_decode(b64_sps,strlen(b64_sps),d->sps->b_wptr,sizeof(value));
			d->pps=allocb(sizeof(value),0);
			d->pps->b_wptr+=b64_decode(b64_pps,strlen(b64_pps),d->pps->b_wptr,sizeof(value));
		}
	}
	return 0;
}
Exemplo n.º 8
0
static int authcheck_md5(aClient *cptr, anAuthStruct *as, char *para)
{
static char buf[512];
int	i, r;
char *saltstr, *hashstr;

	if (!para)
		return -1;
	r = parsepass(as->data, &saltstr, &hashstr);
	if (r == 0) /* Old method without salt: b64(MD5(<pass>)) */
	{
		char result[16];
		
		DoMD5(result, para, strlen(para));
		if ((i = b64_encode(result, sizeof(result), buf, sizeof(buf))))
		{
			if (!strcmp(buf, as->data))
				return 2;
			else
				return -1;
		} else
			return -1;
	} else {
		/* New method with salt: b64(MD5(MD5(<pass>)+salt)) */
		char result1[MAXSALTLEN+16+1];
		char result2[16];
		char rsalt[MAXSALTLEN+1];
		int rsaltlen;
		
		/* First, decode the salt to something real... */
		rsaltlen = b64_decode(saltstr, rsalt, sizeof(rsalt));
		if (rsaltlen <= 0)
			return -1;
		
		/* Then hash the password (1st round)... */
		DoMD5(result1, para, strlen(para));

		/* Add salt to result */
		memcpy(result1+16, rsalt, rsaltlen); /* b64_decode already made sure bounds are ok */

		/* Then hash it all together again (2nd round)... */
		DoMD5(result2, result1, rsaltlen+16);
		
		/* Then base64 encode it all and we are done... */
		if ((i = b64_encode(result2, sizeof(result2), buf, sizeof(buf))))
		{
			if (!strcmp(buf, hashstr))
				return 2;
			else
				return -1;
		} else
			return -1;
	}
	return -1; /* NOTREACHED */
}
Exemplo n.º 9
0
static int authcheck_ripemd160(aClient *cptr, anAuthStruct *as, char *para)
{
char buf[512];
int i, r;
char *saltstr, *hashstr;

	if (!para)
		return -1;
	r = parsepass(as->data, &saltstr, &hashstr);
	if (r)
	{
		/* New method with salt: b64(RIPEMD160(RIPEMD160(<pass>)+salt)) */
		char result1[MAXSALTLEN+20+1];
		char result2[20];
		char rsalt[MAXSALTLEN+1];
		int rsaltlen;
		RIPEMD160_CTX hash;
		
		/* First, decode the salt to something real... */
		rsaltlen = b64_decode(saltstr, rsalt, sizeof(rsalt));
		if (rsaltlen <= 0)
			return -1;

		/* Then hash the password (1st round)... */
		RIPEMD160_Init(&hash);
		RIPEMD160_Update(&hash, para, strlen(para));
		RIPEMD160_Final(result1, &hash);
		/* Add salt to result */
		memcpy(result1+20, rsalt, rsaltlen); /* b64_decode already made sure bounds are ok */

		/* Then hash it all together again (2nd round)... */
		RIPEMD160_Init(&hash);
		RIPEMD160_Update(&hash, result1, rsaltlen+20);
		RIPEMD160_Final(result2, &hash);
		/* Then base64 encode it all and we are done... */
		if ((i = b64_encode(result2, sizeof(result2), buf, sizeof(buf))))
		{
			if (!strcmp(buf, hashstr))
				return 2;
			else
				return -1;
		} else
			return -1;
	} else {
		/* OLD auth */
		if ((i = b64_encode(RIPEMD160(para, strlen(para), NULL), 20, buf, sizeof(buf))))
		{
			if (!strcmp(buf, as->data))
				return 2;
			else
				return -1;
		} else
			return -1;
	}
}
Exemplo n.º 10
0
void interactive_kernel_loop() {
    char *buff = (char*) 0x10000;
    uint32_t len = 0x20000 - 0x10000;
    char *decodebuff = (char*) 0x20000;
    uint32_t decodebufflen = 0x30000 - 0x20000;
    int status = 0;
    while (1) {
        status = uart_getln(buff, len);
        if (status == 0) {
            uart_puts(uart_newline);
            if (str_startswith(buff, "b64 ")) {
                uint32_t bytes_decoded = b64_decode(buff+4, decodebuff, decodebufflen);
                uart_puts("base64 decoded #bytes: ");
                char tmp[32];
                uint32_t tmplen = ARR_LEN(tmp);
                uart_puts(str_int_to_str(bytes_decoded, tmp, tmplen));
                uart_puts(uart_newline);
                // Copy the code of bootstrap_decoded_binary somewhere safe.
                uint32_t func_len = 64; // wild guess
                mem_cpy((uint32_t)bootstrap_decoded_binary, 0x30000, func_len);
                // Call bootstrap_decoded_binary from that safe location
                BRANCHTO(0x30000);
            } else if (str_startswith(buff, "m ")) {
                inspect_memory(buff+2);
            } else if (str_startswith(buff, "r ")) {
                inspect_reg(buff+2);
            } else if (str_startswith(buff, "icky")) {
                uart_puts(yoo);
            } else if (str_startswith(buff, "usr0")) {
                if (pr0) {
                    switch_to_user_process(pr0);
                }
            } else if (str_startswith(buff, "freloc")) {
                char tmp[32];
                uint32_t tmplen = ARR_LEN(tmp);
                uint32_t func_len = ((uint32_t) str_parse_int) - ((uint32_t) str_len);
                mem_cpy((uint32_t)str_len, 0x30000, func_len);
                uart_puts(str_int_to_str(CALL_1(0x30000, "xyz"), tmp, tmplen));
            } else if (str_startswith(buff, "version")) {
                uart_puts(version);
                uart_puts("\r\n");
            } else {
                int strlen = str_len(buff) - 1;
                int j = 0;
                for (; strlen != -1; --strlen, ++j) {
                    decodebuff[j] = buff[strlen];
                }
                decodebuff[j] = 0;
                uart_puts(decodebuff);
            }
        }
        uart_puts(uart_newline);
    }
}
Exemplo n.º 11
0
char *decode(EncodeFormat format, const char *src, size_t srclen, size_t &dstlen)
{
	switch (format)
	{
	case ENCODE_BASE64:
	default:
		return b64_decode(src, srclen, dstlen);
	case ENCODE_HEX:
		return (char *) hexToBytes(src, srclen, dstlen);
	}
}
Exemplo n.º 12
0
int decode_ip( const char *buf )
{
	size_t len = strlen( buf );
	char targ[25];
	struct in_addr ia;

	b64_decode( buf, (unsigned char *)targ, 25 );
	ia = *( struct in_addr * )targ;
	if( len == 8 )  /* IPv4 */
		return ia.s_addr;
	return 0;
}
Exemplo n.º 13
0
int main( int argc, char** argv )
{
  FILE* infile = stdin;
  char* input = NULL;
  size_t inputlen = 0;
  int dec = 0;

  if ( argc < 2 )
  {
    usage();
    return 0;
  }

  if ( !strcmp( argv[1], "enc" ) )
    dec = 0;
  else if ( !strcmp( argv[1], "dec" ) )
    dec = 1;
  else
  {
    usage();
    return 0;
  }

  if ( argc >= 3 )
  {
    if ((infile = fopen(argv[2], "r")) == NULL)
    {
			warn("Cannot open input file: %s", argv[2]);
			exit(1);
    }
  }

  {
    size_t inputlen = 0;
    char* input = read_entire_file( infile, &inputlen );

    {
      char* out = calloc( 1, 2*inputlen );
      size_t len = 0;
      if ( dec )
        len = b64_decode( input, inputlen, out );
      else
        len = b64_encode( input, inputlen, out );
      {
        size_t i = 0;
        for ( ; i < len; i++ )
          fputc( out[ i ], stdout );
      }
      free( out );
    }
  }
  return 0;
}
Exemplo n.º 14
0
int cpi_util_decode_str(cpi_t *p_cpi, char *str, int size, void *data, int *p_size)
{
    size_t ret = b64_decode(str, size, p_cpi->tmp_buff, CPI_MAX_RESULT_SIZE);

    /*! failed to decode */
    if( (ret == 0) || (ret > CPI_MAX_RESULT_SIZE) ) { return CPI_FAIL; }

    /*! return decoded data, respecting max sizes */
    memcpy(data, p_cpi->tmp_buff, (ret+1 > *p_size) ? *p_size : ret+1);

    return CPI_OK;
}
Exemplo n.º 15
0
const char *decode_ip(char *buf)
{
    char targ[25];
    char blah[128];
    bzero(blah,128);

    b64_decode(buf, targ, 25);
    if (strlen(buf) <= 8)
        return inet_ntoa(*(struct in_addr *)targ);
    else
        return(inet_ntop(AF_INET6,targ,blah,INET6_ADDRSTRLEN));
}
Exemplo n.º 16
0
static void on_header_value(ebb_request* request, const char *at, size_t length, int header_index)
{
    ebb_request_info *reqinfo = (ebb_request_info *)(request->data);
    ebb_connection *conn = reqinfo->conn;
    ebb_connection_info *conninfo = (ebb_connection_info *)(conn->data);

    if (reqinfo->parsing_host_header)
    {
        if (length+1 > sizeof(reqinfo->host))
        {
            reqinfo->host[0] = 0;
        }
        else
        {
            memcpy(reqinfo->host, at, length);
            reqinfo->host[length] = 0;
        }
        reqinfo->parsing_host_header = false;
    }

    if (reqinfo->parsing_auth_header)
    {
        if (length > 6)
        {
            if (0 == memcmp(at, "Basic ", 6))
            {
                if (NULL != (reqinfo->auth = calloc(1, (length-6)+1)))
                {
                    b64_decode(reqinfo->auth, at + 6, length-6);
                    LOG_DEBUG("auth='%s'", reqinfo->auth);
                }
            }
        }
        reqinfo->parsing_auth_header = false;
    }

    if (reqinfo->parsing_ifmodifiedsince_header)
    {
        char str[512];
        if (length < sizeof(str))
        {
            memcpy(str, at, length);
            str[length] = 0;
            conninfo->ifmodifiedsince = tdate_parse(str);
            LOG_DEBUG("tdate_parse %s = %u", str, conninfo->ifmodifiedsince);
        }
        reqinfo->parsing_ifmodifiedsince_header = false;
    }
}
Exemplo n.º 17
0
//------------------------------------------------------------------------------
// returns message signature generated from a URI path, a nonce 
// and postdata, message signature is created as a follows:
// 
//   hmac_sha512(path + sha256(nonce + postdata), b64decode(secret)) 
//
// and the result is converted in a base64 string: 
std::string KClient::signature(const std::string& path, 
			    const std::string& nonce, 
			    const std::string& postdata) const
{
   // add path to data to encrypt
   std::vector<unsigned char> data(path.begin(), path.end());

   // concatenate nonce and postdata and compute SHA256
   std::vector<unsigned char> nonce_postdata = sha256(nonce + postdata);

   // concatenate path and nonce_postdata (path + sha256(nonce + postdata))
   data.insert(data.end(), nonce_postdata.begin(), nonce_postdata.end());

   // and compute HMAC
   return b64_encode( hmac_sha512(data, b64_decode(secret_)) );
}
Exemplo n.º 18
0
char* MD5CredentialData(const char* userName, const char* password, const char* nonce) {

    int len = 0, lenNonce = 0, totLen = 0;

    char cnonce      [64];
    char digest      [16];
    char base64      [64];
    char base64Nonce [64];
    char token      [512];
    char* md5Digest = NULL;
    char ch          [3];

    memset(digest,      0, 16);
    memset(base64,      0, 64);
    memset(base64Nonce, 0, 64);
    memset(cnonce,      0, 64);
    memset(token,       0, 512);
    sprintf(ch, ":");

    sprintf(token, "%s:%s", userName, password);
    len = strlen(token);

    // H(username:password)
    calculateMD5((void*)token, len, digest);

    // B64(H(username:password))
    len = b64_encode((char*)base64, digest, 16);


    // decode nonce from stored base64 to bin
    strcpy(cnonce, nonce);
    lenNonce = b64_decode(cnonce, cnonce);

    memcpy(base64Nonce, base64, len);
    memcpy(&base64Nonce[len], ch, 1);
    memcpy(&base64Nonce[len+1], cnonce, lenNonce);

    totLen = len + 1 + lenNonce;

    memset(digest, 0, 16);
    calculateMD5(base64Nonce, totLen, digest);
    b64_encode(base64, digest, 16);

    // return new value
    md5Digest = stringdup(base64);
    return md5Digest;
}
Exemplo n.º 19
0
Arquivo: test.c Projeto: cjhdev/base64
int main(int argc, char **argv)
{
    const char test[] =
"Redistribution and use in source and binary forms, with or without\n"
"modification, are permitted provided that the following conditions are met:\n"
"\n"
"1. Redistributions of source code must retain the above copyright notice, this\n"
"   list of conditions and the following disclaimer.\n"
"2. Redistributions in binary form must reproduce the above copyright notice,\n"
"   this list of conditions and the following disclaimer in the documentation\n"
"   and/or other materials provided with the distribution.\n"

"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n"
"ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n"
"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n"
"DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n"
"ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n"
"(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
"LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n"
"ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n"
"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n"
"SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.";


    printf("message:\n");
    printf("%s\n\n", test);

    uint8_t *b1 = malloc(b64_encoded_size(strlen(test))+1);
    uint8_t *b2 = malloc(strlen(test)+1);
    
    size_t size = b64_encode(b1, (uint8_t *)test, strlen(test));
    b1[size] = 0;

    printf("encoded base64: \n%s\n\n",  b1);
    
    if(b64_decode(b2, b1, size, &size)){
        printf("decoding error!\n");
        exit(EXIT_SUCCESS);
    }

    b2[size] = 0;
    
    printf("decoded again: \n%s\n\n",  b2);
    
    exit(EXIT_SUCCESS);
}
Exemplo n.º 20
0
static int
parse_msg(char *tbuf, char **ndx, int *t_size, fko_ctx_t ctx)
{
    if((*t_size = strcspn(*ndx, ":")) < 1)
        return(FKO_ERROR_INVALID_DATA_DECODE_MESSAGE_MISSING);

    if (*t_size > MAX_SPA_MESSAGE_SIZE)
        return(FKO_ERROR_INVALID_DATA_DECODE_MESSAGE_TOOBIG);

    strlcpy(tbuf, *ndx, *t_size+1);

    if(ctx->message != NULL)
        free(ctx->message);

    ctx->message = calloc(1, *t_size+1); /* Yes, more than we need */

    if(ctx->message == NULL)
        return(FKO_ERROR_MEMORY_ALLOCATION);

    if(b64_decode(tbuf, (unsigned char*)ctx->message) < 0)
        return(FKO_ERROR_INVALID_DATA_DECODE_MESSAGE_DECODEFAIL);

    if(ctx->message_type == FKO_COMMAND_MSG)
    {
        /* Require a message similar to: 1.2.3.4,<command>
        */
        if(validate_cmd_msg(ctx->message) != FKO_SUCCESS)
        {
            return(FKO_ERROR_INVALID_DATA_DECODE_MESSAGE_VALIDFAIL);
        }
    }
    else
    {
        /* Require a message similar to: 1.2.3.4,tcp/22
        */
        if(validate_access_msg(ctx->message) != FKO_SUCCESS)
        {
            return(FKO_ERROR_INVALID_DATA_DECODE_ACCESS_VALIDFAIL);
        }
    }

    *ndx += *t_size + 1;
    return FKO_SUCCESS;
}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
	char  ch;

	if (argc == 1) {
		usage(argv[0]);
		exit (1);
	}

	while ((ch = getopt(argc, argv, "e:d:h")) > 0) {
		switch (ch) {
			case 'e':
				b64_encode(optarg);
				break;
			case 'd':
				b64_decode(optarg);
				break;
			case 'h':
				usage(argv[0]);
				exit (0);
			default:
				usage(argv[0]);
				exit (1);
		}
	}

	{
		char* p = "²Ë";
		char buf[32];
		strcpy(buf, p);
		p = buf;
		p++;
		*p = 0;
		b64_encode(buf);
		strcpy(buf, "²ËÆ×");
		p = buf;
		p++;
		b64_encode(p);
	}

	exit (0);
}
Exemplo n.º 22
0
static void apply_config(SpeexECState *s){
	if (s->state_str!=NULL){
		size_t buflen=strlen(s->state_str);
		uint8_t *buffer=alloca(buflen);
		SpeexEchoStateBlob *blob;
		if ((buflen=b64_decode(s->state_str,strlen(s->state_str),buffer,buflen))<=0){
			ms_error("Could not decode base64 %s",s->state_str);
			return;
		}
		blob=speex_echo_state_blob_new_from_memory(buffer,buflen);
		if (blob==NULL){
			ms_error("Could not create blob from config string");
			return;
		}
		if (speex_echo_ctl(s->ecstate, SPEEX_ECHO_SET_BLOB, blob)!=0){
			ms_error("Could not apply speex echo blob !");
		}
		speex_echo_state_blob_free(blob);
		ms_message("speex echo state restored.");
	}	
}
Exemplo n.º 23
0
int main (int argc, char *argv[])
{
	//unsigned int i = 0;
	unsigned char b64_block[64] = {0}, aes_block[48]= {0}, decoded_block[48] = {0};

	while (read(0, b64_block , 64))
	{
		memset(aes_block, 0, sizeof(aes_block) );
		memset(decoded_block, 0, sizeof(decoded_block) );


		b64_decode((char*) aes_block, (char*) b64_block, 64);

		aes_128_decrypt_msg(decoded_block, aes_block, 48, secret_key, ECB, NULL);
	

		write(1, decoded_block, pkcs7_strip(decoded_block, 48));
		
	}

	return 0;
}
Exemplo n.º 24
0
static void ldapserverE(struct parser_context *ctx,
			struct tagstack_entry *e)
{
    struct gq_config *c = peek_tag(ctx->stack, 1)->data;
    GqServer *server = e->data;

    if (strcasecmp(server->pwencoding, "Base64") == 0 && server->bindpw[0]) {
	GByteArray *o = g_byte_array_new();
	b64_decode(o, server->bindpw, strlen(server->bindpw));

	server->bindpw = g_malloc(o->len + 1);
	strncpy(server->bindpw, (gchar*)o->data, o->len); /* UTF-8 OK */
	server->bindpw[o->len] = 0;
    } else if (server->bindpw[0] && server->pwencoding[0]) {
	XMLhandleError(ctx, _("Unsupported password encoding"));
    }

    canonicalize_ldapserver(server);
    gq_server_list_add(gq_server_list_get(), server);

    e->data = NULL;
    e->free_data = NULL;
}
Exemplo n.º 25
0
Arquivo: ub64.c Projeto: inetric/b64
int
main(int argc, char **argv)
{
    FILE *in;
    unsigned char buff[0x2000];
    size_t fr = 0;
    b64_t b;

    if (argc < 2) return 1;

    in = fopen(argv[1], "rb");
    if (!in) return 1;

    b64_init(&b);

    while ((fr = fread(buff, 1, sizeof buff, in)) > 0) {
        size_t r = fr;
        b64_decode(&b, buff, r, buff, &r);
        fwrite(buff, 1, r, stdout);
    }
    fclose(in);

    return 0;
};
Exemplo n.º 26
0
bool Session::initialize()
{
  // Get URN's wich are supported by this addon
  if (!license_type_.empty())
  {
    GetSupportedDecrypterURN(dashtree_.adp_pssh_);
    xbmc->Log(ADDON::LOG_DEBUG, "Supported URN: %s", dashtree_.adp_pssh_.first.c_str());
  }

  // Open mpd file
  size_t paramPos = mpdFileURL_.find('?');
  dashtree_.base_url_ = (paramPos == std::string::npos)? mpdFileURL_:mpdFileURL_.substr(0, paramPos);

  paramPos = dashtree_.base_url_.find_last_of('/', dashtree_.base_url_.length());
  if (paramPos == std::string::npos)
  {
    xbmc->Log(ADDON::LOG_ERROR, "Invalid mpdURL: / expected (%s)", mpdFileURL_.c_str());
    return false;
  }
  dashtree_.base_url_.resize(paramPos + 1);

  if (!dashtree_.open(mpdFileURL_.c_str()) || dashtree_.empty())
  {
    xbmc->Log(ADDON::LOG_ERROR, "Could not open / parse mpdURL (%s)", mpdFileURL_.c_str());
    return false;
  }
  xbmc->Log(ADDON::LOG_INFO, "Successfully parsed .mpd file. Download speed: %0.4f Bytes/s", dashtree_.download_speed_);

  if (dashtree_.encryptionState_ == dash::DASHTree::ENCRYTIONSTATE_ENCRYPTED)
  {
    xbmc->Log(ADDON::LOG_ERROR, "Unable to handle decryption. Unsupported!");
    return false;
  }

  uint32_t min_bandwidth(0), max_bandwidth(0);
  {
    int buf;
    xbmc->GetSetting("MINBANDWIDTH", (char*)&buf); min_bandwidth = buf;
    xbmc->GetSetting("MAXBANDWIDTH", (char*)&buf); max_bandwidth = buf;
  }

  // create SESSION::STREAM objects. One for each AdaptationSet
  unsigned int i(0);
  const dash::DASHTree::AdaptationSet *adp;

  for (std::vector<STREAM*>::iterator b(streams_.begin()), e(streams_.end()); b != e; ++b)
    SAFE_DELETE(*b);
  streams_.clear();

  while ((adp = dashtree_.GetAdaptationSet(i++)))
  {
    streams_.push_back(new STREAM(dashtree_, adp->type_));
    STREAM &stream(*streams_.back());
    stream.stream_.prepare_stream(adp, width_, height_, min_bandwidth, max_bandwidth);

    switch (adp->type_)
    {
    case dash::DASHTree::VIDEO:
      stream.info_.m_streamType = INPUTSTREAM_INFO::TYPE_VIDEO;
      break;
    case dash::DASHTree::AUDIO:
      stream.info_.m_streamType = INPUTSTREAM_INFO::TYPE_AUDIO;
      break;
    case dash::DASHTree::TEXT:
      stream.info_.m_streamType = INPUTSTREAM_INFO::TYPE_TELETEXT;
      break;
    default:
      break;
    }
    stream.info_.m_pID = i;
    strcpy(stream.info_.m_language, adp->language_.c_str());

    UpdateStream(stream);

  }

  // Try to initialize an SingleSampleDecryptor
#if 1
  if (dashtree_.encryptionState_)
  {
    if (dashtree_.protection_key_.size()!=16 || license_data_.empty())
      return false;

    uint8_t ld[1024];
    unsigned int ld_size(1024);
    b64_decode(license_data_.c_str(), license_data_.size(), ld, ld_size);

    const uint8_t *uuid((uint8_t*)strstr((const char*)ld, "{UUID}"));
    unsigned int license_size = uuid ? ld_size + 36 -6: ld_size;

    //Build up proto header
    AP4_DataBuffer init_data;
    init_data.Reserve(512);
    uint8_t *protoptr(init_data.UseData());
    *protoptr++ = 18; //id=16>>3=2, type=2(flexlen)
    *protoptr++ = 16; //length of key
    memcpy(protoptr, dashtree_.protection_key_.data(), 16);
    protoptr += 16;
    //-----------
    *protoptr++ = 34;//id=32>>3=4, type=2(flexlen)
    do {
      *protoptr++ = static_cast<uint8_t>(license_size & 127);
      license_size >>= 7;
      if (license_size)
        *(protoptr - 1) |= 128;
      else
        break;
    } while (1);
    if (uuid)
    {
      static const uint8_t hexmap[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
      memcpy(protoptr, ld, uuid - ld);
      protoptr += uuid - ld;
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[3]) >> 4];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[3]) & 15];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[2]) >> 4];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[2]) & 15];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[1]) >> 4];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[1]) & 15];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[0]) >> 4];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[0]) & 15];
      *protoptr++ = '-';
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[5]) >> 4];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[5]) & 15];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[4]) >> 4];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[4]) & 15];
      *protoptr++ = '-';
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[7]) >> 4];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[7]) & 15];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[6]) >> 4];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[6]) & 15];
      *protoptr++ = '-';
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[8]) >> 4];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[8]) & 15];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[9]) >> 4];
      *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[9]) & 15];
      *protoptr++ = '-';
      for (i = 10; i < 16; ++i)
      {
        *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[i]) >> 4];
        *protoptr++ = hexmap[(uint8_t)(dashtree_.protection_key_.data()[i]) & 15];
      }
      unsigned int sizeleft = ld_size - ((uuid - ld) + 6);
      memcpy(protoptr, uuid+6, sizeleft);
      protoptr += sizeleft;
    }
    else
    {
      memcpy(protoptr, ld, ld_size);
      protoptr += ld_size;
    }
    init_data.SetDataSize(protoptr - init_data.UseData());
    return (single_sample_decryptor_ = CreateSingleSampleDecrypter(init_data))!=0;
  }
Exemplo n.º 27
0
int
httpd_basic_auth(struct evhttp_request *req, char *user, char *passwd, char *realm)
{
  struct evbuffer *evbuf;
  struct evkeyvalq *headers;
  char *header;
  const char *auth;
  char *authuser;
  char *authpwd;
  int len;
  int ret;

  headers = evhttp_request_get_input_headers(req);
  auth = evhttp_find_header(headers, "Authorization");
  if (!auth)
    {
      DPRINTF(E_DBG, L_HTTPD, "No Authorization header\n");

      goto need_auth;
    }

  if (strncmp(auth, "Basic ", strlen("Basic ")) != 0)
    {
      DPRINTF(E_LOG, L_HTTPD, "Bad Authentication header\n");

      goto need_auth;
    }

  auth += strlen("Basic ");

  authuser = b64_decode(auth);
  if (!authuser)
    {
      DPRINTF(E_LOG, L_HTTPD, "Could not decode Authentication header\n");

      goto need_auth;
    }

  authpwd = strchr(authuser, ':');
  if (!authpwd)
    {
      DPRINTF(E_LOG, L_HTTPD, "Malformed Authentication header\n");

      free(authuser);
      goto need_auth;
    }

  *authpwd = '\0';
  authpwd++;

  if (user)
    {
      if (strcmp(user, authuser) != 0)
	{
	  DPRINTF(E_LOG, L_HTTPD, "Username mismatch\n");

	  free(authuser);
	  goto need_auth;
	}
    }

  if (strcmp(passwd, authpwd) != 0)
    {
      DPRINTF(E_LOG, L_HTTPD, "Bad password\n");

      free(authuser);
      goto need_auth;
    }

  free(authuser);

  return 0;

 need_auth:
  len = strlen(realm) + strlen("Basic realm=") + 3;
  header = (char *)malloc(len);
  if (!header)
    {
      evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");
      return -1;
    }

  ret = snprintf(header, len, "Basic realm=\"%s\"", realm);
  if ((ret < 0) || (ret >= len))
    {
      evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");
      return -1;
    }

  evbuf = evbuffer_new();
  if (!evbuf)
    {
      evhttp_send_error(req, HTTP_SERVUNAVAIL, "Internal Server Error");
      return -1;
    }

  headers = evhttp_request_get_output_headers(req);
  evhttp_add_header(headers, "WWW-Authenticate", header);
  evbuffer_add(evbuf, http_reply_401, strlen(http_reply_401));
  evhttp_send_reply(req, 401, "Unauthorized", evbuf);

  free(header);
  evbuffer_free(evbuf);

  return -1;
}
Exemplo n.º 28
0
StringBuffer MailMessage::decodeHeader(StringBuffer line) {

    if (!line || line.empty()) {
        return line;
    }

    size_t startPos = 0;
    StringBuffer ret;
    StringBuffer charset;
    while( (startPos = line.find("=?", startPos)) != StringBuffer::npos) {
        // Skip the '=?'
        startPos += 2;
        // Find the first '?'
        size_t firstMark = line.find("?", startPos);
        if (firstMark == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }
        // Find the second '?'
        size_t secondMark = line.find("?", firstMark+1);
        if (secondMark == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }
        // Find the final '?='
        size_t endPos = line.find("?=", secondMark+1);
        if (endPos == StringBuffer::npos) {
            LOG.error("Invalid encoded header");
            return line;
        }

        charset = line.substr(startPos, firstMark - startPos);
        StringBuffer encoding = line.substr(firstMark+1, secondMark - (firstMark + 1));
        StringBuffer text = line.substr(secondMark+1, endPos - (secondMark + 1));

        if (encoding.icmp("Q")) {
            // quoted-printable
            text.replaceAll("_", " ");
            char* dec = qp_decode(text);
            if (startPos >= 2 &&  ret.length() == 0) {
                ret += line.substr(0, startPos - 2);
            }

            ret += dec;
            delete [] dec;
        }
        else if (encoding.icmp("B")){
        // base64
            char* dec = new char[text.length()];
            int len = b64_decode((void *)dec, text);
            dec[len]=0;
            if (startPos >= 2 &&  ret.length() == 0) {
                ret += line.substr(0, startPos - 2);
            }
            ret += dec;
            delete [] dec;
        }

        startPos = endPos;
    }

    if (ret.length() == 0) {
        ret += line;
    }

    WCHAR* wret = toWideChar(ret, charset);
    ret.set(NULL);
    char* t = toMultibyte(wret);
    ret.set(t);
    if (wret) {delete [] wret;}
    if (t) {delete [] t;}
    return ret;
}
Exemplo n.º 29
0
static int
parse_server_auth(char *tbuf, char **ndx, int *t_size, fko_ctx_t ctx)
{
    if((*t_size = strlen(*ndx)) > 0)
    {
        if (*t_size > MAX_SPA_MESSAGE_SIZE)
        {
            return(FKO_ERROR_INVALID_DATA_DECODE_SRVAUTH_MISSING);
        }
    }
    else
        return FKO_SUCCESS;

    if(  ctx->message_type == FKO_CLIENT_TIMEOUT_ACCESS_MSG
      || ctx->message_type == FKO_CLIENT_TIMEOUT_NAT_ACCESS_MSG
      || ctx->message_type == FKO_CLIENT_TIMEOUT_LOCAL_NAT_ACCESS_MSG)
    {
        /* If we are here then we may still have a server_auth string,
         * or a timeout, or both. So we look for a ':' delimiter.  If
         * it is there we have both, if not we check the message_type
         * again.
        */
        if(strchr(*ndx, ':'))
        {
            *t_size = strcspn(*ndx, ":");

            if (*t_size > MAX_SPA_MESSAGE_SIZE)
                return(FKO_ERROR_INVALID_DATA_DECODE_EXTRA_TOOBIG);

            strlcpy(tbuf, *ndx, *t_size+1);

            if(ctx->server_auth != NULL)
                free(ctx->server_auth);

            ctx->server_auth = calloc(1, *t_size+1); /* Yes, more than we need */
            if(ctx->server_auth == NULL)
                return(FKO_ERROR_MEMORY_ALLOCATION);

            if(b64_decode(tbuf, (unsigned char*)ctx->server_auth) < 0)
                return(FKO_ERROR_INVALID_DATA_DECODE_EXTRA_DECODEFAIL);

            *ndx += *t_size + 1;
        }
    }
    else
    {
        strlcpy(tbuf, *ndx, *t_size+1);

        if(ctx->server_auth != NULL)
            free(ctx->server_auth);

        ctx->server_auth = calloc(1, *t_size+1); /* Yes, more than we need */
        if(ctx->server_auth == NULL)
            return(FKO_ERROR_MEMORY_ALLOCATION);

        if(b64_decode(tbuf, (unsigned char*)ctx->server_auth) < 0)
            return(FKO_ERROR_INVALID_DATA_DECODE_SRVAUTH_DECODEFAIL);
    }

    return FKO_SUCCESS;
}
Exemplo n.º 30
0
/* Decode, decrypt, and parse SPA data into the context.
*/
static int
_rijndael_decrypt(fko_ctx_t ctx, const char *dec_key)
{
    char           *tbuf;
    unsigned char  *ndx;
    unsigned char  *cipher;
    int             cipher_len, pt_len, i, err = 0;

    int             b64_len = strlen(ctx->encrypted_msg);

    /* Now see if we need to add the "Salted__" string to the front of the
     * encrypted data.
    */
    if(strncmp(ctx->encrypted_msg, B64_RIJNDAEL_SALT, strlen(B64_RIJNDAEL_SALT)))
    {
        /* We need to realloc space for the salt.
        */
        tbuf = realloc(ctx->encrypted_msg, b64_len + 12);
        if(tbuf == NULL)
            return(FKO_ERROR_MEMORY_ALLOCATION);

        memmove(tbuf+strlen(B64_RIJNDAEL_SALT), tbuf, b64_len);

        ctx->encrypted_msg = memcpy(tbuf, B64_RIJNDAEL_SALT, strlen(B64_RIJNDAEL_SALT));

        /* Adjust b64_len for added SALT value and Make sure we are still
         * a properly NULL-terminated string (Ubuntu was one system for
         * which this was an issue).
        */
        b64_len += strlen(B64_RIJNDAEL_SALT);
        tbuf[b64_len] = '\0';
    }

    /* Create a bucket for the (base64) decoded encrypted data and get the
     * raw cipher data.
    */
    cipher = malloc(strlen(ctx->encrypted_msg));
    if(cipher == NULL)
        return(FKO_ERROR_MEMORY_ALLOCATION);

    if((cipher_len = b64_decode(ctx->encrypted_msg, cipher)) < 0)
        return(FKO_ERROR_INVALID_DATA);

    /* Create a bucket for the plaintext data and decrypt the message
     * data into it.
    */
    ctx->encoded_msg = malloc(cipher_len);
    if(ctx->encoded_msg == NULL)
        return(FKO_ERROR_MEMORY_ALLOCATION);

    pt_len = rij_decrypt(cipher, cipher_len, dec_key, (unsigned char*)ctx->encoded_msg);

    /* Done with cipher...
    */
    free(cipher);

    /* The length of the decrypted data should be within 32 bytes of the
     * length of the encrypted version.
    */
    if(pt_len < (cipher_len - 32))
        return(FKO_ERROR_DECRYPTION_SIZE);

    /* At this point we can check the data to see if we have a good
     * decryption by ensuring the first field (16-digit random decimal
     * value) is valid and is followed by a colon.  Additional checks
     * are made in fko_decode_spa_data().
    */
    ndx = (unsigned char *)ctx->encoded_msg;
    for(i=0; i<FKO_RAND_VAL_SIZE; i++)
        if(!isdigit(*(ndx++)))
            err++;

    if(err > 0 || *ndx != ':')
        return(FKO_ERROR_DECRYPTION_FAILURE);

    /* Call fko_decode and return the results.
    */
    return(fko_decode_spa_data(ctx));
}