Ejemplo n.º 1
0
int main(int argc, char * argv[]) {
	peopleHead = NULL;
	allMahHashes_employees = ht_create(65536);
	allMahHashes_guests = ht_create(65536);
	int32_t fileSize = 0;
	FILE* file = NULL;
	size_t bytes = 0;
	ssize_t read = 0;
	char * line = NULL;
	char interString[MAX * 4];

	//get Logreader arguements
	logread_args args = opt_parser(argc, argv, 1);
	//Verify integrity and hopefully the syntax should be right

	fileSize = fsize(args.logName);
	if (fileSize > 15) {
		unsigned int salt[] = { 12345, 54321 };
		FILE * encrypted_file = fopen(args.logName, "r");
		FILE * decrypted = fopen("tempblahman", "w+");
		do_crypt(encrypted_file, decrypted, DECRYPT, args.token,
				strlen(args.token), (unsigned char *) salt);
		rename("tempblahman", args.logName);
	} else {
		invalid();
	}

	file = fopen(args.logName, "r");
	//Line by line apply the options
	while ((read = getline(&line, &bytes, file)) != -1 && fileSize > 10) {

		int len = strlen(line);
		fileSize = fileSize - len;
		// RERUN COMMANDS CAUZE LOGIC!
		sprintf(interString, "./logappend %s", line);
		int tempc;
		char ** tempv = argv_split(interString, &tempc);
		logappend_args temp = opt_parser_log(tempc, tempv);
		buildDataStructs(&temp);
		bzero(interString, MAX * 4);
		argv_free(tempv);
		// FINISH LOGICZ
	}
	doBadThings(&args);

	unsigned int salt[] = { 12345, 54321 };
	FILE * decrypted_file = fopen(args.logName, "r");
	FILE * encrypted = fopen("tempblahman", "w+");
	do_crypt(decrypted_file, encrypted, ENCRYPT, args.token, strlen(args.token),
			(unsigned char *) salt);
	rename("tempblahman", args.logName);

	return 0;
}
Ejemplo n.º 2
0
static int xmp_read(const char *path, char *buf, size_t size, off_t offset,
        struct fuse_file_info *fi)
{
    FILE *f, *memstream;
    int res;
    char pathbuf[BUFSIZE];
    char *membuf;
    size_t memsize;

    (void) fi;
    f = fopen(_xmp_fullpath(pathbuf, path, BUFSIZE), "r");
    memstream = open_memstream(&membuf, &memsize);
    if (f == NULL || memstream == NULL)
        return -errno;

    char attrbuf[8];
    ssize_t attr_len = getxattr(pathbuf, ENCRYPTED_ATTR, attrbuf, 8);
    int crypt_action = AES_PASSTHRU;
    if(attr_len != -1 && !memcmp(attrbuf, "true", 4)){
        crypt_action = AES_DECRYPT;
    }

    xmp_state *state = (xmp_state *)(fuse_get_context()->private_data);
    do_crypt(f, memstream, crypt_action, state->key);
    fflush(memstream);
    fseek(memstream, offset, SEEK_SET);
    res = fread(buf, 1, size, memstream);
    fclose(memstream);

    if (res == -1)
        res = -errno;

    fclose(f);
    return res;
}
Ejemplo n.º 3
0
static int xmp_create(const char* path, mode_t mode, struct fuse_file_info* fi) {
	char fpath[PATH_MAX];
	xmp_getfullpath(fpath, path);
	
    (void) fi;
    (void) mode;

	FILE *fd = fopen(fpath, "wb+");

	fprintf(stderr, "CREATE: fpath: %s\n", fpath);

	if(!do_crypt(fd, fd, ENCRYPT, ENCFS_DATA->passkey)){
		fprintf(stderr, "Create: do_crypt failed\n");
    }

	fprintf(stderr, "Create: encryption done correctly\n");

	fclose(fd);

	if(setxattr(fpath, XATRR_ENCRYPTED_FLAG, "true", 4, 0)){
    	fprintf(stderr, "error setting xattr of file %s\n", fpath);
    	return -errno;
   	}
   	fprintf(stderr, "Create: file xatrr correctly set %s\n", fpath);
   
    return 0;
}
Ejemplo n.º 4
0
static int xmp_create(const char* path, mode_t mode, struct fuse_file_info* fi) {

    (void) fi;
    (void) mode;
    char buf[BUFSIZE];

    FILE *res;
    res = fopen(_xmp_fullpath(buf, path, BUFSIZE), "w");
    if(res == NULL)
        return -errno;

    FILE *tmp = tmpfile();
    xmp_state *state = (xmp_state *)(fuse_get_context()->private_data);
    do_crypt(tmp, res, AES_ENCRYPT, state->key);
    fclose(tmp);

    if(fsetxattr(fileno(res), ENCRYPTED_ATTR, "true", 4, 0)){
        return -errno;
    }

    fclose(res);


    return 0;
}
Ejemplo n.º 5
0
static int enc_create(const char* path, mode_t mode, struct fuse_file_info* fi) {


  char fpath[PATH_MAX];
  enc_fullpath(fpath, path);


  (void) fi;
  (void) mode;

  FILE *f = fopen(fpath, "wb+");

  fprintf(stderr, "CREATE: fpath: %s\n", fpath);

  /* It is okay to encrypt a file into itself as long as it's empty
   *	otherwise the contents of the file would be erased.
   */

  if(!do_crypt(f, f, ENCRYPT, ENC_DATA->password)){
    fprintf(stderr, "Create: do_crypt failed\n");
  }

  fprintf(stderr, "Create: encryption done correctly\n");

  fclose(f);

  if(setxattr(fpath, XATRR_ENCRYPTED_FLAG, ENCRYPTED, 4, 0)){
    fprintf(stderr, "error setting xattr of file %s\n", fpath);
    return -errno;
  }
  fprintf(stderr, "Create: file xatrr correctly set %s\n", fpath);


  return 0;
}
Ejemplo n.º 6
0
int enc_file(const char* path){
    const char* tmp_name;
    const char* new_path = rewritepath(path);
    FILE *enc_fp, *dec_fp;

    if(getencattr(new_path) != 0)
        return 1;

    /* Open decrypted copy */
    dec_fp = fopen(new_path, "r");
    /* Make encrypted copy at tmp_name */
    tmp_name = tmp_path(new_path);
    enc_fp = fopen(tmp_name, "w");
    do_crypt(dec_fp, enc_fp, 1, xmp_data->xmp_key);
    /* Close both copies */
    fclose(dec_fp);
    fclose(enc_fp);
    /* Remove the decrypted copy */
    remove(new_path);
    /* Rename encrypted copy to original name */
    rename(tmp_name, new_path);
    fprintf(stderr, "Enc! New: %s Tmp: %s\n", new_path, tmp_name);
    /* Set the encryption attr */
    setencattr(new_path, 1);
    free((void*)new_path);
    free((void*)tmp_name);
    return 0;
}
Ejemplo n.º 7
0
static bool do_test_cbc(test_vector_t *test)
{
	crypter_t *crypter;

	crypter = lib->crypto->create_crypter(lib->crypto, ENCR_AES_CBC,
										  test->key.len);
	if (!crypter)
	{
		DBG1(DBG_APP, "algorithm %N or key length (%d bits) not supported",
			 encryption_algorithm_names, ENCR_AES_CBC, test->key.len * 8);
		return FALSE;
	}
	if (!crypter->set_key(crypter, test->key))
	{
		DBG1(DBG_APP, "failed to set key");
		crypter->destroy(crypter);
		return FALSE;
	}
	if (!do_crypt(crypter, test))
	{
		crypter->destroy(crypter);
		return FALSE;
	}
	crypter->destroy(crypter);
	return TRUE;
}
Ejemplo n.º 8
0
static int encfs_read(const char *path, char *buf, size_t size, off_t offset,
		    struct fuse_file_info *fi)
{
	// initialize file and temp files for memory storage
	// also xattr data information 
	FILE *file;
	FILE *tempfile;
	char *tempdata;
	size_t tempsize;
	
	char xattrval[8];
	ssize_t xattrlen;
	
	// default action is to pass
	int action = PASS;
	
	int res;
	
	//fuse to make directory not root
	char fpath[PATH_MAX];
	encfs_fullpath(fpath, path);

	(void) fi;
	
	// open file
	file = fopen(fpath, "r");
	if (file == NULL)
		return -errno;
		
	// opem memory stream
	tempfile = open_memstream(&tempdata, &tempsize);
	if (tempfile == NULL)
		return -errno;

	// check if decrypting or now, if it is encrypted then we do
	// otherwise do nothing
	xattrlen = getxattr(fpath, ENC_ATTR, xattrval, 8);
	if(xattrlen != -1 && strcmp(xattrval, ENCRYPTED) == 0) {
		action = DECRYPT;
	}
	
	do_crypt(file, tempfile, action, ENC_DATA->key);
	fclose(file);

	// flush/write temp file in memory in user space
	fflush(tempfile);
	// seek according to the offset from memory
	fseek(tempfile, offset, SEEK_SET);
	
	// open up temp file and read
	res = fread(buf, 1, size, tempfile);
	if (res == -1)
		res = -errno;
	
	// close temp file
	fclose(tempfile);

	return res;
}
Ejemplo n.º 9
0
Archivo: bank.c Proyecto: evanqi/atm
void send_no_user(Bank *bank)
{
    unsigned char *out = (unsigned char *)calloc(10000, sizeof(unsigned char));
    char *response = (char *) calloc(3, sizeof(char));
    response = "nouser";
    do_crypt(bank, (unsigned char *)response, out, 1);
    bank_send(bank, (char*) out, strlen((char *)out));
}
Ejemplo n.º 10
0
void
main()
{
	U_LONG key[2], plain[2], cipher[2], answer[2];
	int i;
	int test;
	int fail;

	for(test=0;!feof(stdin);test++){
		get8(key);
		do_setkey(key);
		printf(" K: "); put8(key);

		get8(plain);
		printf(" P: "); put8(plain);

		get8(answer);
		printf(" C: "); put8(answer);


		for(i=0;i<2;i++)
			cipher[i] = plain[i];
		do_crypt(cipher, 0);

		for(i=0;i<2;i++)
			if(cipher[i] != answer[i])
				break;
		fail = 0;
		if(i != 2){
			printf(" Encrypt FAIL");
			fail++;
		}
		do_crypt(cipher, 1);
		for(i=0;i<2;i++)
			if(cipher[i] != plain[i])
				break;
		if(i != 2){
			printf(" Decrypt FAIL");
			fail++;
		}
		if(fail == 0)
			printf(" OK");
		printf("\n");
	}
}
Ejemplo n.º 11
0
static int xmp_write(const char *path, const char *buf, size_t size,
        off_t offset, struct fuse_file_info *fi)
{
    FILE *f, *memstream;
    int res;
    char pathbuf[BUFSIZE];
    char *membuf;
    size_t memsize;

    (void) fi;
    xmp_state *state = (xmp_state *)(fuse_get_context()->private_data);
    f = fopen(_xmp_fullpath(pathbuf, path, BUFSIZE), "r");
    memstream = open_memstream(&membuf, &memsize);

    if (memstream == NULL)
        return -errno;

    char attrbuf[8];
    ssize_t attr_len = getxattr(pathbuf, ENCRYPTED_ATTR, attrbuf, 8);
    int encrypted = 0;
    if(attr_len != -1 && !memcmp(attrbuf, "true", 4)){
        encrypted = 1;
    }

    if(f != NULL){
        do_crypt(f, memstream, (encrypted ? AES_DECRYPT : AES_PASSTHRU), state->key);
        fclose(f);
    }

    fseek(memstream, offset, SEEK_SET);
    res = fwrite(buf, 1, size, memstream);
    fflush(memstream);
    f = fopen(pathbuf, "w");

    fseek(memstream, 0, SEEK_SET);
    do_crypt(memstream, f, (encrypted ? AES_ENCRYPT : AES_PASSTHRU), state->key);
    fclose(memstream);

    if (res == -1)
        res = -errno;

    fclose(f);
    return res;
}
Ejemplo n.º 12
0
int dec_file_copy(const char* path, const char* dest_path){
    const char* new_path = rewritepath(path);
    FILE *enc_fp, *dec_fp;

    /* Open encrypted copy */
    enc_fp = fopen(new_path, "r");
    /* Make decrypted copy at tmp_name */
    dec_fp = fopen(dest_path, "w");
    if(getencattr(new_path) == 1)
        do_crypt(enc_fp, dec_fp, 0, xmp_data->xmp_key);
    else
        do_crypt(enc_fp, dec_fp, -1, xmp_data->xmp_key);
    /* Close both copies */
    fclose(dec_fp);
    fclose(enc_fp);
    fprintf(stderr, "Dec Copy! Src: %s Dest: %s\n", new_path, dest_path);
    free((void*)new_path);
    return 0;
}
Ejemplo n.º 13
0
void cryptWrapper(logappend_args * args, int32_t type) {
	uint32_t salt[] = { 12345, 54321 };
	int32_t fileSize = fsize(args->logName);
	if (fileSize < 16 && type == 0)
		return;
	FILE * encrypted_file = fopen(args->logName, "r");
	FILE * decrypted = fopen("tempblahman", "w");
	do_crypt(encrypted_file, decrypted, type, args->token, strlen(args->token),
			(unsigned char *) salt);
	rename("tempblahman", args->logName);
}
Ejemplo n.º 14
0
static int xmp_read(const char *path, char *buf, size_t size, off_t offset,
		    struct fuse_file_info *fi)
{
	(void)fi;
	int res=0;
	int action;
	ssize_t vsize = 0;
	char *tval = NULL;

	char fpath[PATH_MAX];
	xmp_getfullpath(fpath, path);

	vsize = getxattr(fpath, XATRR_ENCRYPTED_FLAG, NULL, 0);
	tval = malloc(sizeof(*tval)*(vsize));
	vsize = getxattr(fpath, XATRR_ENCRYPTED_FLAG, tval, vsize);

	fprintf(stderr, "Size: %zu, offset: %zu.\n", size, offset);

	/* If the specified attribute doesn't exist or it's set to false */
	if (vsize < 0 || memcmp(tval, "false", 5) == 0){
		if(errno == ENODATA){
			fprintf(stderr, "Read: No %s attribute set\n", XATRR_ENCRYPTED_FLAG);
		}
		action = COPY;
	}
	else if (memcmp(tval, "true", 4) == 0){
		action = DECRYPT;
		fprintf(stderr, "Read: file is encrypted, need to decrypt\n");
	}

	const char *tpath = ftemp(fpath, ".read");
	FILE *dfd = fopen(tpath, "wb+");
	FILE *fd = fopen(fpath, "rb");

	if(!do_crypt(fd, dfd, action, ENCFS_DATA->passkey)){
		fprintf(stderr, "Encryption failed, error code: %d\n", res);
    	}

    fseek(dfd, 0, SEEK_END);
   	size_t tflen = ftell(dfd);
    fseek(dfd, 0, SEEK_SET);

   	res = fread(buf, 1, tflen, dfd);
    	if (res == -1) res = -errno;

	fclose(fd);
	fclose(dfd);
	remove(tpath);
	free(tval);

	return res;
}
Ejemplo n.º 15
0
static int xmp_read(const char *path, char *buf, size_t size, off_t offset,
		    struct fuse_file_info *fi)
{
	int res;
	FILE* fp;
	FILE* mfp;
	char* mval;
	size_t mlen;
	char xattrval[8];
	ssize_t xattrlen;
	int action = -1;
	
	char filepath[PATH_MAX];
	xmp_extendPath(filepath, path);

	(void) fi;
	
	//open file we want to read
	fp = fopen(filepath, "r");
	if(fp == NULL){
		return -errno;
	}
	
	//ready memstream
	mfp = open_memstream(&mval, &mlen);
	if(mfp == NULL){
		return -errno;
	}
	
	//check if file is encrypted
	xattrlen = getxattr(filepath, "user.encrypted", xattrval, 8);
	if (xattrlen != -1 && memcmp(xattrval, "true", 4) == 0){
		action = 0;
	}
	
	//decrypt file if encrypted, or copy if isn't encrypted
	do_crypt(fp, mfp, action, XMP_INFO -> pass);
	
	//wait for mfp to fully load, cleanup
	fflush(mfp);
	fseek(mfp, offset, SEEK_SET);
	fclose(fp);
	res = fread(buf, 1, size, mfp);
	fclose(mfp);
	if (res == -1)
		res = -errno;
	
	return res;
}
Ejemplo n.º 16
0
/*
 * Given a CTCP SED argument 'str', it attempts to unscramble the text
 * into something more sane.  If the 'key' is not the one used to scramble
 * the text, the results are unpredictable.  This is probably the point.
 *
 * Note that the retval MUST be at least 'BIG_BUFFER_SIZE + 1'.  This is
 * not an oversight -- the retval is passed is to do_ctcp() which requires
 * a big buffer to scratch around (The decrypted text could be a CTCP UTC
 * which could expand to a larger string of text.)
 */
char 	*decrypt_msg (char *str, Crypt *key)
{
    char	*buffer = (char *)new_malloc(BIG_BUFFER_SIZE + 1);
    char	*ptr;

    if ((ptr = do_crypt(str, key, 0)) != NULL)
    {
        strlcpy(buffer, ptr, CRYPT_BUFFER_SIZE + 1);
        new_free(&ptr);
    }
    else
        strlcat(buffer, str, CRYPT_BUFFER_SIZE + 1);

    return buffer;
}
Ejemplo n.º 17
0
static unsigned int
geode_aes_crypt(struct geode_aes_op *op)
{
	u32 flags = 0;
	unsigned long iflags;
	int ret;

	if (op->len == 0)
		return 0;

	/* If the source and destination is the same, then
	 * we need to turn on the coherent flags, otherwise
	 * we don't need to worry
	 */

	flags |= (AES_CTRL_DCA | AES_CTRL_SCA);

	if (op->dir == AES_DIR_ENCRYPT)
		flags |= AES_CTRL_ENCRYPT;

	/* Start the critical section */

	spin_lock_irqsave(&lock, iflags);

	if (op->mode == AES_MODE_CBC) {
		flags |= AES_CTRL_CBC;
		_writefield(AES_WRITEIV0_REG, op->iv);
	}

	if (!(op->flags & AES_FLAGS_HIDDENKEY)) {
		flags |= AES_CTRL_WRKEY;
		_writefield(AES_WRITEKEY0_REG, op->key);
	}

	ret = do_crypt(op->src, op->dst, op->len, flags);
	BUG_ON(ret);

	if (op->mode == AES_MODE_CBC)
		_readfield(AES_WRITEIV0_REG, op->iv);

	spin_unlock_irqrestore(&lock, iflags);

	return op->len;
}
Ejemplo n.º 18
0
static int cmd_password_hset(RedisModuleCtx *ctx, RedisModuleString **argv, int argc) {
    RedisModuleCallReply *reply;
    size_t len;
    char crypt_buf[64];
    char *hash;

    if (argc != 4) {
        RedisModule_WrongArity(ctx);
        return REDISMODULE_OK;
    }

    hash = do_crypt(RedisModule_StringPtrLen(argv[3], &len), crypt_buf, sizeof(crypt_buf));
    if (!hash) {
        RedisModule_ReplyWithError(ctx, "ERR hash error");
        return REDISMODULE_ERR;
    }
    reply = RedisModule_Call(ctx, "HSET", "ssc!", argv[1], argv[2], hash);
    RedisModule_ReplyWithCallReply(ctx, reply);

    return REDISMODULE_OK;
}
Ejemplo n.º 19
0
static int xmp_create(const char* path, mode_t mode, struct fuse_file_info* fi)
{
	int res;
	FILE* fp;
	FILE* mfp;
	char* mval;
	size_t mlen;
	
    (void) fi;
    (void) mode;

	char filepath[PATH_MAX];
	xmp_extendPath(filepath, path);
	
	//open new file
    fp = fopen(filepath, "w");
    if(fp == NULL){
		return -errno;
	}
	
	//prep mstream
	mfp = open_memstream(&mval, &mlen);
	if(mfp == NULL){
		return -errno;
	}
	
	//encrypt new file
	do_crypt(mfp, fp, 1, XMP_INFO -> pass);
	fclose(mfp);
	
	//set xattr flag to encrypted
	res = setxattr(filepath, "user.encrypted", "true", 4, 0);
	printf("%d\n", res);
	if(res){
		return -errno;
	}
	fclose(fp);
	
    return 0;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[])
{
	if(argc == 3)
	{
		FILE *fin = fopen(argv[1], "r");
		char buffer[100*60];
		fgets(buffer, 100, fin);
		while(fgets(&buffer[strlen(buffer)-1], 100, fin));
		buffer[strlen(buffer)-1] = '\0';
		char *rawbuffer = base64toraw(buffer);
		FILE *fout = fopen("temp.bin", "wb");
		int i = 0;
		fwrite(rawbuffer, sizeof(char), strlen(buffer)*3/4, fout);
		fclose(fout);
		fclose(fin);

		fin = fopen("temp.bin", "rb");
		fout = fopen(argv[2], "w");
		if(do_crypt(fin, fout, 0)) {
			fclose(fin);
			fclose(fout);
			fin = fopen(argv[2], "r");
			char tempbuffer[100];
			while(fgets(&tempbuffer[0], 100, fin))
				printf("%s", tempbuffer);
		}
		else {
			printf("Something went wrong, decrypt failed\n");
			fclose(fout);
		}

		fclose(fin);
	}
	else {
		printf("Usage: ./s1c7.out input.txt output.txt\n");
	}

	return 0;
}
Ejemplo n.º 21
0
static int xmp_create(const char* path, mode_t mode, struct fuse_file_info* fi) {
	fprintf(stderr, "in create\n");
	FILE *newFile;
	char fullPath[PATH_MAX];
	stopPath(fullPath, path);
	//FILE* outFile;
	//char *outFileText;
	//size_t outFileSize;

	(void)mode;
    (void) fi;

   // int res;
	//outFile=open_memstream(&outFileText,&outFileSize);
	newFile=fopen(fullPath,"w");

	fprintf(stderr, "do_crypts is happening\n\n\n\n");
	if(!do_crypt(newFile, newFile, ENC,key)){
		fprintf(stderr, "do_cryptfailedd\n\n\n\n");
	}


   /* if(res == -1){
	return -errno;
	}*/
	fclose(newFile);

	if(setxattr(fullPath,NAME,"true",strlen("true"),0)){
		fprintf(stderr, "error in xpm create\n\n\n\n\n");

	}
	fprintf(stderr, "leaving create\n");
    

	   //sets attributeds cnositnet name is encrypted failes if the attribute alreads excists could be XATTR_REPLACE should really matter excpeted for maybe deaper security reasons

    return 0;
}
Ejemplo n.º 22
0
static int gostchiper(sc_card_t *card, u8 keyid,
		const char *path_infile, const char *path_outfile,
		const char IV[IV_SIZE], int is_iv, int op_oper)
{
	int r;
	u8 iv[IV_SIZE];

	if (op_oper == OP_ENCRYPT) {
		if (!is_iv) {
			/*  generated random on token  */
			r = sc_get_challenge(card, iv, IV_SIZE);
	if (r) {
				fprintf(stderr, "Error: Generate IV"
						" (get challenge) failed: %s\n",
		        sc_strerror(r));
				return -1;
			}
		}
		else
			memcpy(iv, IV, IV_SIZE);
	}
	return do_crypt(card, keyid, path_infile, path_outfile, iv, op_oper);
}
Ejemplo n.º 23
0
/*
 * crypt_msg: Given plaintext 'str', constructs a body suitable for sending
 * via PRIVMSG or DCC CHAT.
 */
char 	*crypt_msg (char *str, Crypt *key)
{
    char	buffer[CRYPT_BUFFER_SIZE + 1];
    char	thing[6];
    char	*ptr;

    snprintf(thing, 6, "%cSED ", CTCP_DELIM_CHAR);
    *buffer = 0;
    if ((ptr = do_crypt(str, key, 1)))
    {
        if (!*ptr) {
            yell("WARNING: Empty encrypted message, but message "
                 "sent anyway.  Bug?");
        }
        strlcat(buffer, thing, sizeof buffer);
        strlcat(buffer, ptr, sizeof buffer);
        strlcat(buffer, CTCP_DELIM_STR, sizeof buffer);
        new_free(&ptr);
    }
    else
        strlcat(buffer, str, sizeof buffer);

    return malloc_strdup(buffer);
}
static int xmp_read(const char *path, char *buf, size_t size, off_t offset,
		    struct fuse_file_info *fi)
{
	int action = PASS_THROUGH;
	ssize_t valsize = 0;
	char *tmpval = NULL;
	int fd;
	int res;
	char fpath[PATH_MAX];
	xmp_fullpath(fpath, path);
	FILE *stream;
	FILE* inFile = NULL;
    char *buffer;
    size_t len;
	char key_phrase[] = "password";
	
	valsize = getxattr(fpath, XATRR_ENCRYPTED_FLAG, NULL, 0);
	tmpval = malloc(sizeof(*tmpval)*(valsize + 1));
	
	if(!tmpval){
	    perror("malloc of 'tmpval' error");
	    exit(EXIT_FAILURE);
	}
	valsize = getxattr(fpath, XATRR_ENCRYPTED_FLAG, tmpval, valsize);
		/* If the specified attribute doesn't exist or it's set to false */
	if (valsize < 0 || memcmp(tmpval, "false", 5) == 0){
		if(errno == ENOATTR){
			fprintf(stderr, "Read: No %s attribute set\n", XATRR_ENCRYPTED_FLAG);
		}
		fprintf(stderr, "Read: file is unencrypted, leaving crypt_action as pass-through\n");
	}/* If the attribute exists and is true then we need to get size of decrypted file */
	else if (memcmp(tmpval, "true", 4) == 0){
		fprintf(stderr, "Read: file is encrypted, need to decrypt\n");
		action = DECRYPT;
	}
	
 
    
    stream = open_memstream(&buffer, &len);
    if (stream == NULL)
        return -errno;
	(void) fi;
	inFile = fopen(fpath, "rb");
	 if(!inFile){
	perror("infile fopen error");
	return EXIT_FAILURE;
    }
   
   
   
    if(!do_crypt(inFile, stream, action, key_phrase)){
		fprintf(stderr, "do_crypt failed\n");
		/*fd = open(fpath, O_RDONLY);
		if (fd == -1)
			return -errno;

		res = pread(fd, buf, size, offset);
		if (res == -1)
		res = -errno;

		close(fd);
		return res;*/
    }
    res = fread(buf, 1, len, stream);
    if (res == -1)
    	res = -errno;

	fclose(stream);
	fclose(inFile);
	free(tmpval)
	free(buffer);

	return res;
}
Ejemplo n.º 25
0
static int xmp_write(const char *path, const char *buf, size_t size,
		     off_t offset, struct fuse_file_info *fi)
{
	(void) fi;
	(void) offset;

	int res=0;
	int action = COPY;

	ssize_t vsize = 0;
	char *tval = NULL;

	char fpath[PATH_MAX];
	xmp_getfullpath(fpath, path);

	vsize = getxattr(fpath, XATRR_ENCRYPTED_FLAG, NULL, 0);
	tval = malloc(sizeof(*tval)*(vsize));
	vsize = getxattr(fpath, XATRR_ENCRYPTED_FLAG, tval, vsize);

	if (vsize < 0 || memcmp(tval, "false", 5) == 0){
		if(errno == ENODATA){
			fprintf(stderr, "Encryption flag not set, file cannot be read.\n");
		}
		fprintf(stderr, "File unencrypted, reading...\n");
	}
	/* If the attribute exists and is true get size of decrypted file */
	else if (memcmp(tval, "true", 4) == 0){
		fprintf(stderr, "File encrypted, decrypting...\n");
		action = DECRYPT;
	}


	/* If the file to be written to is encrypted */
	if (action == DECRYPT){
		
		FILE *fd = fopen(fpath, "rb+");
		const char *tpath = ftemp(fpath, ".write");
		FILE *dfd = fopen(tpath, "wb+");

		fseek(fd, 0, SEEK_END);
		fseek(fd, 0, SEEK_SET);

		if(!do_crypt(fd, dfd, DECRYPT, ENCFS_DATA->passkey)){
			fprintf(stderr, "Decryption failed, error code: %d\n", res);
    	}

    	fseek(fd, 0, SEEK_SET);

    	res = fwrite(buf, 1, size, dfd);
    	if (res == -1)
		res = -errno;

		fseek(dfd, 0, SEEK_SET);

		if(!do_crypt(dfd, fd, ENCRYPT, ENCFS_DATA->passkey)){
			fprintf(stderr, "Encryption failed, error code: %d\n", res);
		}

		fclose(fd);
		fclose(dfd);
		remove(tpath);
	}
	/* If the file to be written to is unencrypted */
	else if (action == COPY){
		int fd1;
		fprintf(stderr, "File unencrypted, reading...\n");

		fd1 = open(fpath, O_WRONLY);
		if (fd1 == -1)
			return -errno;

		res = pwrite(fd1, buf, size, offset);
		if (res == -1)
			res = -errno;

		close(fd1);
   	}
   	
	free(tval);
	return res;
}
Ejemplo n.º 26
0
INT retrieve_elog(char *host, int port, char *subdir, int ssl, char *experiment,
                  char *uname, char *upwd, int message_id,
                  char attrib_name[MAX_N_ATTR][NAME_LENGTH], char attrib[MAX_N_ATTR][NAME_LENGTH], char *text)
/********************************************************************\

  Routine: retrive_elog

  Purpose: Retrive an ELog entry for edit/reply

  Input:
    char   *host            Host name where ELog server runs
    int    port             ELog server port number
    char   *subdir          Subdirectoy to elog server
    int    ssl              Flag for using SSL layer
    char   *uname           User name
    char   *upwd            User password
    int    message_id       Message to retrieve
    char   *attrib_name     Attribute names
    char   *attrib          Attribute values
    char   *text            Message text

  Function value:
    EL_SUCCESS              Successful completion

\********************************************************************/
{
   int i, n, first, index, sock;
   char str[256], encrypted_passwd[256], *ph, *ps;
#ifdef HAVE_SSL
   SSL *ssl_con = NULL;
#endif

   if (ssl)                     /* avoid compiler warning */
      sock = 0;

   sock = elog_connect(host, port);
   if (sock < 0)
      return sock;

#ifdef HAVE_SSL
   if (ssl)
      if (ssl_connect(sock, &ssl_con) < 0) {
         printf("elogd server does not run SSL protocol\n");
         return -1;
      }
#endif

   /* compose request */
   strcpy(request, "GET /");
   strlcpy(str, experiment, sizeof(str));
   url_encode(str, sizeof(str));
   if (subdir[0] && experiment[0])
      sprintf(request + strlen(request), "%s/%s/%d?cmd=download", subdir, str, message_id);
   else if (subdir[0])
      sprintf(request + strlen(request), "%s/%d?cmd=download", subdir, message_id);
   else if (experiment[0])
      sprintf(request + strlen(request), "%s/%d?cmd=download", str, message_id);
   strcat(request, " HTTP/1.0\r\n");

   sprintf(request + strlen(request), "User-Agent: ELOG\r\n");

   first = 1;

   if (uname[0]) {
      if (first)
         sprintf(request + strlen(request), "Cookie: ");
      first = 0;

      sprintf(request + strlen(request), "unm=%s;", uname);
   }

   if (upwd[0]) {
      if (first)
         sprintf(request + strlen(request), "Cookie: ");
      first = 0;

      do_crypt(upwd, encrypted_passwd, sizeof(encrypted_passwd));
      sprintf(request + strlen(request), "upwd=%s;", encrypted_passwd);
   }

   /* finish cookie line */
   if (!first)
      strcat(request, "\r\n");

   strcat(request, "\r\n");

   /* send request */
#ifdef HAVE_SSL
   if (ssl)
      SSL_write(ssl_con, request, strlen(request));
   else
#endif
      send(sock, request, strlen(request), 0);
   if (verbose) {
      printf("Request sent to host:\n");
      puts(request);
   }

   /* receive response */
   memset(response, 0, sizeof(response));
#ifdef HAVE_SSL
   if (ssl)
      i = SSL_read(ssl_con, response, sizeof(response) - 1);
   else
#endif
      i = recv(sock, response, sizeof(response) - 1, 0);
   if (i < 0) {
      perror("Cannot receive response");
      return -1;
   }

   n = i;
   while (i > 0) {
#ifdef HAVE_SSL
      if (ssl)
         i = SSL_read(ssl_con, response + n, sizeof(response) - 1 - n);
      else
#endif
         i = recv(sock, response + n, sizeof(response) - 1 - n, 0);
      if (i > 0)
         n += i;
   }
   response[n] = 0;

#ifdef HAVE_SSL
   if (ssl) {
      SSL_shutdown(ssl_con);
      SSL_free(ssl_con);
   }
#endif

   closesocket(sock);

   if (verbose) {
      printf("Response received:\n");
      puts(response);
   }

   /* check response status */
   if (strstr(response, "$@MID@$:")) {
      /* separate attributes and message */

      ph = strstr(response, "========================================\n");

      /* skip first line */
      ps = strstr(response, "$@MID@$:");
      while (*ps && *ps != '\n')
         ps++;
      while (*ps && (*ps == '\n' || *ps == '\r'))
         ps++;

      for (index = 0; index < MAX_N_ATTR; index++) {
         if (ps >= ph)
            break;

         strlcpy(attrib_name[index], ps, NAME_LENGTH);
         if (strchr(attrib_name[index], ':'))
            *(strchr(attrib_name[index], ':')) = 0;

         ps += strlen(attrib_name[index]) + 2;
         strlcpy(attrib[index], ps, NAME_LENGTH);

         for (i = 0; i < NAME_LENGTH; i++) {
            if (attrib[index][i] == '\r' || attrib[index][i] == '\n')
               attrib[index][i] = 0;

            if (attrib[index][i] == 0)
               break;
         }

         ps += strlen(attrib[index]);
         while (*ps && (*ps == '\n' || *ps == '\r'))
            ps++;
      }

      attrib_name[index][0] = 0;
      attrib[index][0] = 0;

      ph = strchr(ph, '\n') + 1;
      if (*ph == '\r')
         ph++;

      strlcpy(text, ph, TEXT_SIZE);

      return 1;
   }

   if (strstr(response, "302 Found")) {
      if (strstr(response, "Location:")) {
         if (strstr(response, "fail"))
            printf("Error: Invalid user name or password\n");
         else {
            strncpy(str, strstr(response, "Location:") + 10, sizeof(str));
            if (strchr(str, '?'))
               *strchr(str, '?') = 0;
            if (strchr(str, '\n'))
               *strchr(str, '\n') = 0;
            if (strchr(str, '\r'))
               *strchr(str, '\r') = 0;

            if (strrchr(str, '/'))
               printf("Message successfully transmitted, ID=%s\n", strrchr(str, '/') + 1);
            else
               printf("Message successfully transmitted, ID=%s\n", str);
         }
      }
   } else if (strstr(response, "Logbook Selection"))
      printf("Error: No logbook specified\n");
   else if (strstr(response, "enter password"))
      printf("Error: Missing or invalid password\n");
   else if (strstr(response, "form name=form1"))
      printf("Error: Missing or invalid user name/password\n");
   else
      printf("Error transmitting message\n");

   return 0;
}
Ejemplo n.º 27
0
INT submit_elog(char *host, int port, int ssl, char *subdir, char *experiment,
                char *uname, char *upwd,
                int reply,
                int quote_on_reply,
                int edit,
                int download,
                int suppress,
                int encoding,
                char attrib_name[MAX_N_ATTR][NAME_LENGTH],
                char attrib[MAX_N_ATTR][NAME_LENGTH],
                int n_attr,
                char *text, char afilename[MAX_ATTACHMENTS][256],
                char *buffer[MAX_ATTACHMENTS], INT buffer_size[MAX_ATTACHMENTS])
/********************************************************************\

  Routine: submit_elog

  Purpose: Submit an ELog entry

  Input:
    char   *host            Host name where ELog server runs
    in     port             ELog server port number
    int    ssl              SSL flag
    char   *subdir          Subdirectoy to elog server
    char   *uname           User name
    char   *upwd            User password
    int    reply            Reply to existing message
    int    edit             Edit existing message
    int    download         Download existing message
    int    suppress         Suppress Email notification
    int    encoding         0:ELCode,1:plain,2:HTML
    char   *attrib_name     Attribute names
    char   *attrib          Attribute values
    char   *text            Message text

    char   afilename[]      File names of attachments
    char   *buffer[]        Attachment contents
    INT    buffer_size[]    Size of buffer in bytes

  Function value:
    EL_SUCCESS              Successful completion

\********************************************************************/
{
   int status, sock, i, n, header_length, content_length, index;
   char host_name[256], boundary[80], str[80], encrypted_passwd[256], *p, *old_encoding;
   char old_attrib_name[MAX_N_ATTR+1][NAME_LENGTH], old_attrib[MAX_N_ATTR+1][NAME_LENGTH];
   struct hostent *phe;
#ifdef HAVE_SSL
   SSL *ssl_con = NULL;
#endif

   /* get local host name */
   gethostname(host_name, sizeof(host_name));

   phe = gethostbyname(host_name);
   if (phe == NULL) {
      perror("Cannot retrieve host name");
      return -1;
   }
   phe = gethostbyaddr(phe->h_addr, sizeof(int), AF_INET);
   if (phe == NULL) {
      perror("Cannot retrieve host name");
      return -1;
   }

   /* if domain name is not in host name, hope to get it from phe */
   if (strchr(host_name, '.') == NULL)
      strcpy(host_name, phe->h_name);

   if (edit || download) {
      if (edit)
         status = retrieve_elog(host, port, subdir, ssl, experiment, uname, upwd, edit,
                                old_attrib_name, old_attrib, old_text);
      else
         status = retrieve_elog(host, port, subdir, ssl, experiment, uname, upwd, download,
                                old_attrib_name, old_attrib, old_text);

      if (status != 1)
         return status;

      /* update attributes */
      for (index = 0; index < n_attr; index++) {
         for (i = 0; i < MAX_N_ATTR && old_attrib_name[i][0]; i++)
            if (equal_ustring(attrib_name[index], old_attrib_name[i]))
               break;

         if (old_attrib_name[i][0])
            strlcpy(old_attrib[i], attrib[index], NAME_LENGTH);
      }

      /* copy attributes */
      for (i = 0; i < MAX_N_ATTR && old_attrib_name[i][0]; i++) {
         strlcpy(attrib_name[i], old_attrib_name[i], NAME_LENGTH);
         strlcpy(attrib[i], old_attrib[i], NAME_LENGTH);
      }

      n_attr = i;

      if (text[0] == 0)
         strlcpy(text, old_text, TEXT_SIZE);
   }
   
   if (download) {
      if (strstr(response, "$@MID@$:"))
         printf("%s", strstr(response, "$@MID@$:"));
      else
         printf("%s", response);
      return 1;
   }

   if (reply) {
      status =
          retrieve_elog(host, port, subdir, ssl, experiment, uname, upwd, reply,
                        old_attrib_name, old_attrib, old_text);

      if (status != 1)
         return status;

      /* update attributes */
      for (index = 0; index < n_attr; index++) {
         for (i = 0; i < MAX_N_ATTR && old_attrib_name[i][0]; i++)
            if (equal_ustring(attrib_name[index], old_attrib_name[i]))
               break;

         if (old_attrib_name[i][0])
            strlcpy(old_attrib[i], attrib[index], NAME_LENGTH);
      }

      /* copy attributes */
      for (i = 0; i < MAX_N_ATTR && old_attrib_name[i][0]; i++) {
         if (equal_ustring(old_attrib_name[i], "Reply to") || equal_ustring(old_attrib_name[i], "Date")) {
            attrib_name[i][0] = 0;
            attrib[i][0] = 0;
         } else {
            strlcpy(attrib_name[i], old_attrib_name[i], NAME_LENGTH);
            strlcpy(attrib[i], old_attrib[i], NAME_LENGTH);
         }
      }

      n_attr = i;

      /* check encoding */
      old_encoding = "plain";

      for (i = 0; i < n_attr; i++)
         if (equal_ustring(attrib_name[i], "encoding"))
            break;

      if (i < n_attr)
         old_encoding = attrib[i];

      if (quote_on_reply) {
         strlcpy(new_text, text, sizeof(new_text));

         /* precede old text with "> " */
         text[0] = 0;
         p = old_text;

         do {
            if (strchr(p, '\n')) {
               *strchr(p, '\n') = 0;

               if (old_encoding[0] == 'H') {
                  strlcat(text, "> ", TEXT_SIZE);
                  strlcat(text, p, TEXT_SIZE);
                  strlcat(text, "<br>\n", TEXT_SIZE);
               } else {
                  strlcat(text, "> ", TEXT_SIZE);
                  strlcat(text, p, TEXT_SIZE);
                  strlcat(text, "\n", TEXT_SIZE);
               }

               p += strlen(p) + 1;
               if (*p == '\n')
                  p++;
            } else {
               if (old_encoding[0] == 'H') {
                  strlcat(text, "> ", TEXT_SIZE);
                  strlcat(text, p, TEXT_SIZE);
                  strlcat(text, "<p>\n", TEXT_SIZE);
               } else {
                  strlcat(text, "> ", TEXT_SIZE);
                  strlcat(text, p, TEXT_SIZE);
                  strlcat(text, "\n\n", TEXT_SIZE);
               }

               break;
            }

         } while (1);

         strlcat(text, new_text, TEXT_SIZE);
      }
   }

   sock = elog_connect(host, port);
   if (sock < 0)
      return sock;

#ifdef HAVE_SSL
   if (ssl)
      if (ssl_connect(sock, &ssl_con) < 0) {
         printf("elogd server does not run SSL protocol\n");
         return -1;
      }
#endif

   content_length = 100000;
   for (i = 0; i < MAX_ATTACHMENTS; i++)
      if (afilename[i][0])
         content_length += buffer_size[i];
   content = (char *)malloc(content_length);
   if (content == NULL) {
      printf("Not enough memory\n");
      return -1;
   }

   /* compose content */
   srand((unsigned) time(NULL));
   sprintf(boundary, "---------------------------%04X%04X%04X", rand(), rand(), rand());
   strcpy(content, boundary);
   strcat(content, "\r\nContent-Disposition: form-data; name=\"cmd\"\r\n\r\nSubmit\r\n");

   if (uname[0])
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"unm\"\r\n\r\n%s\r\n", boundary, uname);

   if (upwd[0]) {
      do_crypt(upwd, encrypted_passwd, sizeof(encrypted_passwd));
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"upwd\"\r\n\r\n%s\r\n", boundary,
              encrypted_passwd);
   }

   if (experiment[0])
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"exp\"\r\n\r\n%s\r\n", boundary, experiment);

   if (reply)
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"reply_to\"\r\n\r\n%d\r\n", boundary, reply);

   if (edit) {
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"edit_id\"\r\n\r\n%d\r\n", boundary, edit);
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"skiplock\"\r\n\r\n1\r\n", boundary);
   }

   if (suppress)
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"suppress\"\r\n\r\n1\r\n", boundary);

   if (encoding == 0)
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"encoding\"\r\n\r\nELCode\r\n", boundary);
   else if (encoding == 1)
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"encoding\"\r\n\r\nplain\r\n", boundary);
   else if (encoding == 2)
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"encoding\"\r\n\r\nHTML\r\n", boundary);

   for (i = 0; i < n_attr; i++) {
      strcpy(str, attrib_name[i]);
      if (str[0]) {
         stou(str);
         sprintf(content + strlen(content),
                 "%s\r\nContent-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", boundary, str, attrib[i]);
      }
   }

   if (text[0])
      sprintf(content + strlen(content),
              "%s\r\nContent-Disposition: form-data; name=\"Text\"\r\n\r\n%s\r\n%s\r\n",
              boundary, text, boundary);

   content_length = strlen(content);
   p = content + content_length;

   for (i = 0; i < MAX_ATTACHMENTS; i++)
      if (afilename[i][0]) {
         sprintf(p,
                 "Content-Disposition: form-data; name=\"attfile%d\"; filename=\"%s\"\r\n\r\n",
                 i + 1, afilename[i]);

         content_length += strlen(p);
         p += strlen(p);
         memcpy(p, buffer[i], buffer_size[i]);
         p += buffer_size[i];
         strcpy(p, boundary);
         strcat(p, "\r\n");

         content_length += buffer_size[i] + strlen(p);
         p += strlen(p);
      }

   /* compose request */
   strcpy(request, "POST /");
   if (subdir[0])
      sprintf(request + strlen(request), "%s/", subdir);
   if (experiment[0]) {
      strcpy(str, experiment);
      url_encode(str, sizeof(str));
      sprintf(request + strlen(request), "%s/", str);
   }
   strcat(request, " HTTP/1.0\r\n");

   sprintf(request + strlen(request), "Content-Type: multipart/form-data; boundary=%s\r\n", boundary);
   if (port != 80)
      sprintf(str, "%s:%d", host, port);
   else
      sprintf(str, "%s", host);
   sprintf(request + strlen(request), "Host: %s\r\n", str);
   sprintf(request + strlen(request), "User-Agent: ELOG\r\n");
   sprintf(request + strlen(request), "Content-Length: %d\r\n", content_length);

   strcat(request, "\r\n");

   header_length = strlen(request);

   /*
      {
      FILE *f;
      f = fopen("elog.log", "w");
      fwrite(request, header_length+content_length, 1, f);
      fclose(f);
      }
    */

   /* send request */
#ifdef HAVE_SSL
   if (ssl)
      SSL_write(ssl_con, request, header_length);
   else
#endif
      send(sock, request, header_length, 0);
   if (verbose) {
      printf("Request sent to host:\n");
      puts(request);
   }

   /* send content */
#ifdef HAVE_SSL
   if (ssl)
      SSL_write(ssl_con, content, content_length);
   else
#endif
      send(sock, content, content_length, 0);
   if (verbose) {
      printf("Content sent to host:\n");
      puts(content);
   }

   /* receive response */
   memset(response, 0, sizeof(response));
#ifdef HAVE_SSL
   if (ssl)
      i = SSL_read(ssl_con, response, sizeof(response) - 1);
   else
#endif
      i = recv(sock, response, sizeof(response) - 1, 0);
   if (i < 0) {
      perror("Cannot receive response");
      return -1;
   }

   /* discard remainder of response */
   n = i;
   while (i > 0) {
#ifdef HAVE_SSL
      if (ssl)
         i = SSL_read(ssl_con, response + n, sizeof(response) - 1 - n);
      else
#endif
         i = recv(sock, response + n, sizeof(response) - 1 - n, 0);
      if (i > 0)
         n += i;
   }
   response[n] = 0;

#ifdef HAVE_SSL
   if (ssl) {
      SSL_shutdown(ssl_con);
      SSL_free(ssl_con);
   }
#endif

   closesocket(sock);

   if (verbose) {
      printf("Response received:\n");
      puts(response);
   }

   /* check response status */
   if (strstr(response, "302 Found")) {
      if (strstr(response, "Location:")) {
         if (strstr(response, "has moved"))
            printf("Error: elogd server has moved to another location\n");
         else if (strstr(response, "fail"))
            printf("Error: Invalid user name or password\n");
         else {
            strncpy(str, strstr(response, "Location:") + 10, sizeof(str));
            if (strchr(str, '?'))
               *strchr(str, '?') = 0;
            if (strchr(str, '\n'))
               *strchr(str, '\n') = 0;
            if (strchr(str, '\r'))
               *strchr(str, '\r') = 0;

            if (strrchr(str, '/'))
               printf("Message successfully transmitted, ID=%s\n", strrchr(str, '/') + 1);
            else
               printf("Message successfully transmitted, ID=%s\n", str);
         }
      } else
         printf("Message successfully transmitted\n");
   } else if (strstr(response, "Logbook Selection"))
      printf("Error: No logbook specified\n");
   else if (strstr(response, "enter password"))
      printf("Error: Missing or invalid password\n");
   else if (strstr(response, "form name=form1"))
      printf("Error: Missing or invalid user name/password\n");
   else if (strstr(response, "Error: Attribute")) {
      if (strstr(response, "not existing")) {
         strncpy(str, strstr(response, "Error: Attribute") + 27, sizeof(str));
         if (strchr(str, '<'))
            *strchr(str, '<') = 0;
         printf("Error: Non existing attribute option \"%s\"\n", str);
      } else {
         strncpy(str, strstr(response, "Error: Attribute") + 20, sizeof(str));
         if (strchr(str, '<'))
            *strchr(str, '<') = 0;
         printf("Error: Missing required attribute \"%s\"\n", str);
      }
   } else
      printf("Error transmitting message\n");

   return 1;
}
Ejemplo n.º 28
0
static bool do_test_mct(test_vector_t *test)
{
	crypter_t *crypter;
	chunk_t prev, *input, *output;
	int i, j;

	crypter = lib->crypto->create_crypter(lib->crypto, ENCR_AES_CBC,
										  test->key.len);
	if (!crypter)
	{
		DBG1(DBG_APP, "algorithm %N or key length (%d bits) not supported",
			 encryption_algorithm_names, ENCR_AES_CBC, test->key.len * 8);
		return FALSE;
	}
	input = ctx.decrypt ? &test->cipher : &test->plain;
	output = ctx.decrypt ? &test->plain : &test->cipher;
	if (crypter->get_block_size(crypter) != input->len)
	{
		DBG1(DBG_APP, "MCT only works for input with a length of one block");
		crypter->destroy(crypter);
		return FALSE;
	}
	prev = chunk_alloca(input->len);
	/* assume initial IV as previous output */
	*output = chunk_clone(test->iv);
	for (i = 0; i < 100; i++)
	{
		if (i > 0)
		{	/* we copied the original lines already */
			fprintf(ctx.out, "COUNT = %d\n", i);
			fprintf(ctx.out, "KEY = %+B\n", &test->key);
			fprintf(ctx.out, "IV = %+B\n", &test->iv);
			fprintf(ctx.out, "%s = %+B\n",
					ctx.decrypt ? "CIPHERTEXT" : "PLAINTEXT", input);
		}
		if (!crypter->set_key(crypter, test->key))
		{
			DBG1(DBG_APP, "failed to set key");
			return FALSE;
		}
		for (j = 0; j < 1000; j++)
		{
			/* store previous output as it is used as input after next */
			memcpy(prev.ptr, output->ptr, prev.len);
			chunk_free(output);
			if (!do_crypt(crypter, test))
			{
				crypter->destroy(crypter);
				return FALSE;
			}
			/* prepare the next IV (our API does not allow incremental calls) */
			if (ctx.decrypt)
			{
				memcpy(test->iv.ptr, input->ptr, test->iv.len);
			}
			else
			{
				memcpy(test->iv.ptr, output->ptr, test->iv.len);
			}
			/* the previous output is the next input */
			memcpy(input->ptr, prev.ptr, input->len);
		}
		fprintf(ctx.out, "%s = %+B\n\n",
				ctx.decrypt ? "PLAINTEXT" : "CIPHERTEXT", output);
		/* derive key for next round */
		switch (test->key.len)
		{
			case 16:
				memxor(test->key.ptr, output->ptr, output->len);
				break;
			case 24:
				memxor(test->key.ptr, prev.ptr + 8, 8);
				memxor(test->key.ptr + 8, output->ptr, output->len);
				break;
			case 32:
				memxor(test->key.ptr, prev.ptr, prev.len);
				memxor(test->key.ptr + prev.len, output->ptr, output->len);
				break;
		}
		/* the current output is used as IV for the next round */
		memcpy(test->iv.ptr, output->ptr, test->iv.len);
	}
	crypter->destroy(crypter);
	/* we return FALSE as we print the output ourselves */
	return FALSE;
}
Ejemplo n.º 29
0
static int xmp_write(const char *path, const char *buf, size_t size,
		     off_t offset, struct fuse_file_info *fi)
{
	int res;
	FILE* fp;
	FILE* mfp;
	char* mval;
	size_t mlen;
	char xattrval[8];
	ssize_t xattrlen;
	int action = -1;
	
	char filepath[PATH_MAX];
	xmp_extendPath(filepath, path);

	(void) fi;
	
	//open file we want to write
	fp = fopen(filepath, "r");
	if(fp == NULL){
		return -errno;
	}
	
	//prep mstream
	mfp = open_memstream(&mval, &mlen);
	if(mfp == NULL){
		return -errno;
	}
	
	//check if file is encrypted
	xattrlen = getxattr(filepath, "user.encrypted", xattrval, 8);
	if (xattrlen != -1 && !memcmp(xattrval, "true", 4)){
		action = 0;
	}
	
	//unencrypt if encrypted, otherwise copy
	do_crypt(fp, mfp, action, XMP_INFO -> pass);
	fclose(fp);
	
	//find write area and load
	fseek(mfp, offset, SEEK_SET);
	res = fwrite(buf, 1, size, mfp);
	if (res == -1)
		res = -errno;
	fflush(mfp);
	
	//encrypt if we decrypted
	if(action == 0){
		action = 1;
	}
	
	fp = fopen(filepath, "w");
	fseek(mfp, 0, SEEK_SET);
	do_crypt(mfp, fp, action, XMP_INFO -> pass);
	
	//cleanup
	fclose(mfp);
	fclose(fp);
	
	return res;
}
Ejemplo n.º 30
0
void atm_process_command(ATM *atm, char *command)
{
	unsigned char recvline[1025 + 16 + EVP_MAX_BLOCK_LENGTH], sendline[1025 + 16 + EVP_MAX_BLOCK_LENGTH];
	unsigned char enc_in[1024], dec_in[1025 + EVP_MAX_BLOCK_LENGTH];
	unsigned char *digest, rec_digest[129], *outbuf, iv[16];
	char username[251], *cmd_arg, *arg, user_card_filename[256], pin_in[10], message[1025];
	char cardkey[33], username_cardkey[33];
	int input_error = 1, username_pin, pin, ret, cmd_pos = 0, pos = 0, amt, int_arg, n=0;
	int crypt_len, in_len, digest_len;
	User *current_user;
	FILE *card;
	time_t t, start;
	
	cmd_arg = malloc(251);
	arg = malloc(251);
	outbuf = malloc(1025 + EVP_MAX_BLOCK_LENGTH);
	digest = malloc(129);
	
	//clear strings
	sendline[0] = 0;
	outbuf[0] = 0;
	enc_in[0] = 0;
	
	ret = get_ascii_arg(command, pos, &cmd_arg);
	cmd_pos += ret + 1;
	
	if (strcmp(cmd_arg, "begin-session") == 0){
		//get username
		if(atm->logged_in){
			printf("A user is already logged in\n");
			return;
		}
		
		pos = cmd_pos;
		ret = get_letter_arg(command, pos, &arg);
		if (ret > 0 && ret <= 250){
			pos += ret + 1;
			memcpy(username, arg, ret);
			username[ret] = 0;
			
			//should be no more args
			if(get_ascii_arg(command, pos, &arg) != 0){
				printf("Usage:  begin-session <user-name>\n");
				return;
			}
			
			//send request to bank for User username
			// Write message
			sprintf(message, "%lu authenticate-user %s",atm->counter++, username);
			
			// Compute Digest
			digest_len = do_digest(message, &digest);
			
			// To encrypt: digest_len digest message
			sprintf(enc_in, "%s %s", digest, message);
			
			//null bytes seem to screw things up so try until no null bytes
			do{
				do{
					RAND_bytes(iv, sizeof(iv));
				} while(strlen(iv) < 16);
				crypt_len = do_crypt(enc_in, strlen(enc_in), 1, atm->key, iv, &outbuf);
			} while (strlen(outbuf) != crypt_len || crypt_len == 0);
			//concat iv and outbuf
			strncat(sendline, iv, sizeof(iv));
			strncat(sendline, outbuf, crypt_len);
			atm_send(atm, sendline, crypt_len + sizeof(iv));
			
			//process response from bank
			n = atm_recv(atm,recvline, 1024 + EVP_MAX_BLOCK_LENGTH);
			if(n < 0 ){
				printf("Communication error occurred. Please try again.\n");
				return;
			}

			recvline[n]=0;
			
			//clear strings
			outbuf[0] = 0;
			dec_in[0] = 0;
			
			
			//first 16 bytes are iv, rest is cipher to decrypt
			memcpy(iv, recvline, sizeof(iv));
			in_len = n - sizeof(iv);
			memcpy(dec_in, recvline + sizeof(iv), in_len);
			dec_in[in_len] = 0;
			
			//decrypt cipher
			crypt_len = do_crypt(dec_in, in_len, 0, atm->key, iv, &outbuf);
			
			//first 64 characters are digest, rest is message
			memcpy(rec_digest, outbuf, 128);
			rec_digest[128]=0;
			memcpy(message, outbuf+129, crypt_len - 129);
			message[crypt_len - 129] = 0;
			
			//do_digest on message and verify it matches sent digest
			digest_len = do_digest(message, &digest);
			digest[128]=0;
			if(strcmp(digest, rec_digest) != 0){
				printf("Digests don't match, message was tampered with. Ignorning...\n");
				return;
			}
			
			//check counter
			pos = 0;
			ret = get_digit_arg(message, pos, &int_arg);
			pos += ret + 1;
			if(int_arg < atm->counter){
				//Atm got message with an invalid counter. Ignoring...
				return;
			}
			atm->counter = int_arg + 1;
			
			//process response
			ret = get_ascii_arg(message, pos, &arg);
			if(ret<= 0 ){
				//shouldn't happen bc verifying digest 
				return;
			}
			else{
				if(strcmp("found", arg) == 0){
					pos += ret + 1;
					//username
					atm->current_username = malloc(251);
					ret = get_letter_arg(message, pos, &arg);
					pos += ret + 1;
					strncpy(atm->current_username, arg, strlen(arg));
					atm->current_username[strlen(arg)]=0;
					
					//pin
					ret = get_digit_arg(message, pos, &int_arg);
					pos += ret + 1;
					username_pin = int_arg;
					
					//card
					memcpy(username_cardkey, message+pos, 32);
					username_cardkey[32]=0;
					//look for the card file and check can read
					sprintf(user_card_filename,"%s.card", atm->current_username);
					card = fopen(user_card_filename, "r");
					if(card == NULL){
						printf("Unable to access %s's card - null card\n", atm->current_username);
						return;
					}
					ret = fread(cardkey, 1, sizeof(cardkey), card);
					cardkey[32]=0;
					
					if(strncmp(cardkey, username_cardkey, sizeof(username_cardkey)) != 0){
						printf("Unable to access %s's card - cardkey mismatch\n", atm->current_username);
						return;
					}				 
					
					
					//prompt for pin
					printf("PIN? ");
					fgets(pin_in, 10, stdin);
					pos = 0;
					ret = get_digit_arg(pin_in, pos, &int_arg);
					pin = int_arg;
					pos += ret + 1;
					if(pin != username_pin || get_ascii_arg(pin_in, pos, &arg)){
						printf("Not Authorized\n");
						
						//If 3 failed attempts in 30 seconds, shut down
						if((time(&t) - atm->fail_time1) <= 30){
							printf("There have been 3 failed login attempts in the past 30 seconds.\nPlease wait 2 minutes before trying again.\n");
							sleep(120);
						}
						else{
							atm->fail_time1 = atm->fail_time2;
							atm->fail_time2 = time(&t);
						}
						return;
					}
					
					else{
						printf("Authorized\n");
						atm->logged_in=1;
						atm->current_user = current_user;
						return;
					}
					
				}
				else if(strcmp("not-found", arg) == 0){
					printf("No such user\n");
					return;
				}
			}
			
		}
		else{
			printf("Usage:  begin-sesion <user-name>\n");
		}
	}
	
	
	//Withdraw
	else if (strcmp(cmd_arg, "withdraw") == 0){
		if(!atm->logged_in){
			printf("No user logged in\n");
			return;
		}
		
		//get amt from user input
		pos = cmd_pos;
		ret = get_digit_arg(command, pos, &int_arg);
		if (ret > 0){
			amt = int_arg;
			pos += ret + 1;
			//should be no more args
			if(get_ascii_arg(command, pos, &arg) == 0){
					
				// Write message
				sprintf(message, "%lu withdraw %s %d",atm->counter++, atm->current_username, amt);
				
				// Compute Digest
				digest_len = do_digest(message, &digest);
				
				// To encrypt: digest_len digest message
				sprintf(enc_in, "%s %s", digest, message);
				
				//null bytes seem to screw things up so try until no null bytes
				do{
					do{
						RAND_bytes(iv, sizeof(iv));
					} while(strlen(iv) < 16);
					crypt_len = do_crypt(enc_in, strlen(enc_in), 1, atm->key, iv, &outbuf);
				} while (strlen(outbuf) != crypt_len || crypt_len == 0);
				//concat iv and outbuf
				strncat(sendline, iv, sizeof(iv));
				strncat(sendline, outbuf, crypt_len);
				atm_send(atm, sendline, crypt_len + sizeof(iv));
				
				//process response from bank
				n = atm_recv(atm,recvline, 1024 + EVP_MAX_BLOCK_LENGTH);
				if(n < 0 ){
					printf("Communication error occurred. Please try again.\n");
					return;
				}
				recvline[n]=0;
				
				//clear sendline and outbuf
				outbuf[0] = 0;
				dec_in[0] = 0;
				
				//first 16 bytes are iv, rest is cipher to decrypt
				memcpy(iv, recvline, sizeof(iv));
				in_len = n - sizeof(iv);
				memcpy(dec_in, recvline + sizeof(iv), in_len);
				dec_in[in_len] = 0;
				
				//decrypt cipher
				crypt_len = do_crypt(dec_in, in_len, 0, atm->key, iv, &outbuf);
				
				//first 64 characters are digest, rest is message
				memcpy(rec_digest, outbuf, 128);
				rec_digest[128]=0;
				memcpy(message, outbuf+129, crypt_len - 129);
				message[crypt_len - 129] = 0;
				
				//do_digest on message and verify it matches sent digest
				digest_len = do_digest(message, &digest);
				digest[128]=0;
				if(strcmp(digest, rec_digest) != 0){
					printf("Digests don't match, message was tampered with. Ignorning...\n");
					return;
				}
				
				
				//check counter
				pos = 0;
				ret = get_digit_arg(message, pos, &int_arg);
				pos += ret + 1;
				if(int_arg < atm->counter){
					//ATM got message with an invalid counter. Ignoring...
					return;
				}
				atm->counter = int_arg + 1;
				
				//process response
				ret = get_ascii_arg(message, pos, &arg);
				
				if(strcmp(arg, "success") == 0)
					printf("$%d dispensed\n", amt);
				else if (strcmp(arg, "insufficient-funds") == 0)
					printf("Insufficient funds\n");
				return;
			}
		}
		printf("Usage:  withdraw <amt>\n");
		return;
	}
	
	
	
	else if (strcmp(cmd_arg, "balance") == 0){
		if(!atm->logged_in){
			printf("No user logged in\n");
			return;
		}
		pos = cmd_pos;
		if (get_ascii_arg(command, pos, &arg) != 0){
			printf("Usage:  balance\n");
			return;
		}
		
		// Write message
		sprintf(message, "%lu balance %s",atm->counter++, atm->current_username);
		
		// Compute Digest
		digest_len = do_digest(message, &digest);
		
		// To encrypt: digest_len digest message
		sprintf(enc_in, "%s %s", digest, message);
		
		//null bytes seem to screw things up so try until no null bytes
		do{
			do{
				RAND_bytes(iv, sizeof(iv));
			} while(strlen(iv) < 16);
			crypt_len = do_crypt(enc_in, strlen(enc_in), 1, atm->key, iv, &outbuf);
		} while (strlen(outbuf) != crypt_len || crypt_len == 0);
		//concat iv and outbuf
		strncat(sendline, iv, sizeof(iv));
		strncat(sendline, outbuf, crypt_len);
		atm_send(atm, sendline, crypt_len + sizeof(iv));
			
		
		//process response from bank
		n = atm_recv(atm,recvline, 1024 + EVP_MAX_BLOCK_LENGTH);
		if(n < 0 ){
			printf("Communication error occurred. Please try again.\n");
			return;
		}
		recvline[n]=0;
		
		//clear sendline and outbuf
		outbuf[0] = 0;
		dec_in[0] = 0;
		
		//first 16 bytes are iv, rest is cipher to decrypt
		memcpy(iv, recvline, sizeof(iv));
		in_len = n - sizeof(iv);
		memcpy(dec_in, recvline + sizeof(iv), in_len);
		dec_in[in_len] = 0;
		
		//decrypt cipher
		crypt_len = do_crypt(dec_in, in_len, 0, atm->key, iv, &outbuf);
		
		//first 64 characters are digest, rest is message
		memcpy(rec_digest, outbuf, 128);
		rec_digest[128]=0;
		memcpy(message, outbuf+129, crypt_len - 129);
		message[crypt_len - 129] = 0;
		
		//do_digest on message and verify it matches sent digest
		digest_len = do_digest(message, &digest);
		digest[128]=0;
		if(strcmp(digest, rec_digest) != 0){
			printf("Digests don't match, message was tampered with. Ignorning...\n");
			return;
		}
		
		//check counter
		pos = 0;
		ret = get_digit_arg(message, pos, &int_arg);
		pos += ret + 1;
		if(int_arg < atm->counter){
			//ATM got message with an invalid counter. Ignoring...
			return;
		}
		
		atm->counter = int_arg + 1;
		
		//process response
		ret = get_digit_arg(message, pos, &int_arg);
		
		
		printf("$%d\n", int_arg);
		return;
	}
	
	// log user out - set logged-in to false and username to null
	else if (strcmp(cmd_arg, "end-session") == 0){
		if(!atm->logged_in){
			printf("No user logged in\n");
			return;
		}
		
		free(atm->current_username);
		atm->current_username = NULL;
		atm->logged_in = 0;
		printf("User logged out\n");
		return;
			
	}
	
	else{
		printf("Invalid command\n");
		return;
	}
}