def test_escape_tar_encrypt(self): try: # change to the sub test directory for tar tests os.chdir("testdir11") command = "crypto --tar testtar" child = self.submit_same_esc_passphrase(command) self.assertTrue(file_exists("testtar.tar.crypt")) # test new encrypted archive exists child.close() shutil.move('testtar', 'testtar_temp') decrypt_command = "decrypto testtar.tar.crypt" child = self.submit_same_esc_passphrase(decrypt_command) self.assertTrue(dir_exists(make_path("testtar"))) # test decrypted tar archive exists self.assertTrue(file_exists(make_path("testtar", "esc_test.txt"))) self.assertTrue(file_exists(make_path("testtar", "esc_test2.txt"))) child.close() # cleanup os.remove(make_path("testtar.tar.crypt")) # remove encrypted archive shutil.rmtree(make_path("testtar")) # remove the decrypted, unpacked directory shutil.move('testtar_temp', 'testtar') # move the original tar testing dir back to original path except Exception as e: # return to top level testing directory os.chdir(self.cwd) raise e finally: # return to top level testing directory os.chdir(self.cwd)
def setUp(self): self.cwd = os.getcwd() self.test_dir = "pull-tests/remotefiles" self.test_text_file_dict = {"testfile.txt": "https://raw.githubusercontent.com/bit-store/testfiles/master/doxx/testfile.txt"} self.test_text_file_two_dict = {"testfile": "https://raw.githubusercontent.com/bit-store/testfiles/master/doxx/testfile"} self.test_text_file_three_dict = {"existdir/testfile.txt": "https://raw.githubusercontent.com/bit-store/testfiles/master/doxx/testfile.txt"} self.test_text_file_four_dict = {"nonexistdir/testfile.txt": "https://raw.githubusercontent.com/bit-store/testfiles/master/doxx/testfile.txt"} self.test_multi_text_files_dict = {"testfile.txt": "https://raw.githubusercontent.com/bit-store/testfiles/master/doxx/testfile.txt", "testfile": "https://raw.githubusercontent.com/bit-store/testfiles/master/doxx/testfile"} self.test_multi_text_files_two_dict = {"existdir/testfile.txt": "https://raw.githubusercontent.com/bit-store/testfiles/master/doxx/testfile.txt", "nonexistdir/testfile": "https://raw.githubusercontent.com/bit-store/testfiles/master/doxx/testfile"} self.test_bad_text_file_dict = {"testfile.txt": "https://raw.githubusercontent.com/bit-store/testfiles/master/doxx/nonexistenttextfile.txt"} # remove test files and directories if they exist from last test if file_exists("pull-tests/remotefiles/testfile.txt"): os.remove("pull-tests/remotefiles/testfile.txt") self.assertFalse(file_exists("pull-tests/remotefiles/testfile.txt")) if file_exists("pull-tests/remotefiles/existdir/testfile.txt"): os.remove("pull-tests/remotefiles/existdir/testfile.txt") self.assertFalse(file_exists("pull-tests/remotefiles/existdir/testfile.txt")) if dir_exists("pull-tests/nonexistdir"): shutil.rmtree("pull-tests/nonexistdir") self.assertFalse(dir_exists("pull-tests/nonexistdir"))
def test_crypto_untar_subdirs_archive_cwd(self): shutil.copyfile(self.subdirs_encrypted_archive_sourcepath, self.subdirs_encrypted_archive_destpath) # execute with testdir as the working directory try: os.chdir(self.testdir) command = "decrypto subdirs.tar.crypt" child = self.submit_same_passphrase(command) # directory write occurs in the proper spot self.assertTrue(dir_exists('subdirs')) # unpacked decrypted directory contains unpacked subdirectories self.assertTrue(dir_exists(os.path.join('subdirs', 'dir1'))) self.assertTrue(dir_exists(os.path.join('subdirs', 'dir2'))) # unpacked decrypted directory contains the correct path for unpacked file in subdirectory self.assertTrue(file_exists(os.path.join('subdirs', 'dir1', 'test.txt'))) # the tar archive is deleted, encrypted file is not self.assertFalse(file_exists('subdirs.tar')) self.assertTrue(file_exists('subdirs.tar.crypt')) child.close() # cleanup shutil.rmtree('subdirs') os.remove('subdirs.tar.crypt') os.chdir(self.cwd) except Exception as e: os.chdir(self.cwd) raise e
def test_http_get_binary_file_absent(self): """Test HTTP GET request and write to binary file when it does not exist""" filepath = os.path.join('testfiles', 'testdir', 'test.tar.gz') if file_exists(filepath): os.remove(filepath) http = HTTP("https://github.com/chrissimpkins/six-four/tarball/master") http.get_bin_write_file(filepath) self.assertTrue(file_exists(filepath))
def test_multifile_goodbad_filepath(self): command = "crypto testdir1/test1.txt testdir1/bogusfile.txt" child = self.submit_same_passphrase(command) self.assertTrue(file_exists(make_path("testdir1", "test1.txt.crypt"))) self.assertFalse(file_exists(make_path("testdir1", "bogusfile.txt.crypt"))) #should not be present when original does not exist child.close() # cleanup os.remove(make_path("testdir1", "test1.txt.crypt"))
def test_http_post_binary_file_absent(self): """Test HTTP POST request binary file write when the file does not exist""" filepath = os.path.join('testfiles', 'testdir', 'post.gz') if file_exists(filepath): os.remove(filepath) http = HTTP("http://httpbin.org/gzip") http_data_write = http.post_bin_write_file(filepath) self.assertEqual(True, http_data_write) #test boolean for confirmation of data write self.assertEqual(True, file_exists(filepath))
def test_asciifile_encrypt_multiple_files(self): command = "crypto --armor testdir1/.testfile testdir1/test1.txt" child = self.submit_same_passphrase(command) self.assertTrue(file_exists(make_path("testdir1", ".testfile.crypt"))) self.assertTrue(file_exists(make_path("testdir1", "test1.txt.crypt"))) child.close() # cleanup os.remove(make_path("testdir1", ".testfile.crypt")) os.remove(make_path("testdir1", "test1.txt.crypt"))
def test_unicode_directory_encrypt(self): command = "crypto testdir7" child = self.submit_same_uni_passphrase(command) self.assertTrue(file_exists(make_path("testdir7", "uni_test.txt.crypt"))) #test that new encrypted file exists self.assertTrue(file_exists(make_path("testdir7", "uni_test2.txt.crypt"))) #test that new encrypted file exists child.close() # cleanup os.remove(make_path("testdir7","uni_test.txt.crypt")) os.remove(make_path("testdir7","uni_test2.txt.crypt"))
def test_http_post_binary_file_present_request_overwrite(self): """Test HTTP POST request binary file write when file does exist and request for overwrite""" filepath = os.path.join('testfiles', 'testdir', 'post.gz') if not file_exists(filepath): fw = FileWriter(filepath) fw.write('test') http = HTTP('http://httpbin.org/gzip') response = http.post_bin_write_file(filepath, overwrite_existing=True) self.assertEqual(True, response) self.assertEqual(True, file_exists(filepath))
def test_http_get_binary_file_exists_request_overwrite(self): """Test HTTP GET request and write binary file executes the write when the file exists and overwrite requested""" filepath = os.path.join('testfiles', 'testdir', 'test.tar.gz') fw = FileWriter(filepath) fw.write("test") if not file_exists(filepath): raise RuntimeError("Missing test file for the unit test") http = HTTP("https://github.com/chrissimpkins/six-four/tarball/master") http.get_bin_write_file(filepath, overwrite_existing=True) self.assertTrue(file_exists(filepath))
def test_multifile_encrypt_txt(self): command = "crypto testdir1/test1.txt testdir2/test1.txt" child = self.submit_same_passphrase(command) self.assertTrue(file_exists(make_path("testdir1", "test1.txt.crypt"))) #test that new encrypted file exists self.assertTrue(file_exists(make_path("testdir2", "test1.txt.crypt"))) child.close() # cleanup os.remove(make_path("testdir1","test1.txt.crypt")) os.remove(make_path("testdir2","test1.txt.crypt"))
def test_singledir_file_encrypt(self): command = "crypto testdir2" child = self.submit_same_passphrase(command) child.close() self.assertTrue(file_exists(make_path("testdir2", "test1.txt.crypt"))) self.assertTrue(file_exists(make_path("testdir2", "test2.txt.crypt"))) self.assertFalse(file_exists(make_path("testdir2", "testcrypt.txt.crypt.crypt"))) os.remove(make_path("testdir2","test1.txt.crypt")) os.remove(make_path("testdir2","test2.txt.crypt"))
def test_multifile_encrypt_withdotfile(self): command = "crypto testdir1/test1.txt testdir1/.testfile" child = self.submit_same_passphrase(command) self.assertTrue(file_exists(make_path("testdir1", "test1.txt.crypt"))) self.assertTrue(file_exists(make_path("testdir1", ".testfile.crypt"))) #should encrypt an explicitly included dotfile child.close() # cleanup os.remove(make_path("testdir1", "test1.txt.crypt")) os.remove(make_path("testdir1", ".testfile.crypt"))
def test_multifile_encrypt_image(self): command = "crypto testdir1/star.png testdir1/tiger.jpg" child = self.submit_same_passphrase(command) self.assertTrue(file_exists(make_path("testdir1", "star.png.crypt"))) self.assertTrue(file_exists(make_path("testdir1", "tiger.jpg.crypt"))) child.close() # cleanup os.remove(make_path("testdir1", "star.png.crypt")) os.remove(make_path("testdir1", "tiger.jpg.crypt"))
def test_doxx_pull_zip_archive(self): try: os.chdir(self.zip_pull_dir) run_pull('https://github.com/bit-store/testfiles/raw/master/doxx/pull-tests/packed.zip') self.assertTrue(file_exists('key.yaml')) self.assertTrue(file_exists('test.doxt')) self.assertTrue(file_exists('test2.doxt')) os.chdir(self.cwd) except Exception as e: os.chdir(self.cwd) raise e
def test_multifile_encrypt_withencryptedfile(self): command = "crypto testdir2/test1.txt testdir2/test2.txt testdir2/testcrypt.txt.crypt" child = self.submit_same_passphrase(command) self.assertTrue(file_exists(make_path("testdir2", "test1.txt.crypt"))) self.assertTrue(file_exists(make_path("testdir2", "test2.txt.crypt"))) self.assertFalse(file_exists(make_path("testdir2", "testcrypt.txt.crypt.crypt"))) # assert that did not encrypt previously encrypted file child.close() # cleanup os.remove(make_path("testdir2", "test1.txt.crypt")) os.remove(make_path("testdir2", "test2.txt.crypt"))
def test_decrypt_singlegpgfile_overwrite_shortflag(self): command = "decrypto -o testdir6/test2.txt.gpg" child = pexpect.spawn(command) child.expect("Please enter your passphrase: ") child.sendline("test") child.expect("Please enter your passphrase again: ") child.sendline("test") child.expect("'testdir6/test2.txt.gpg' decrypted to 'testdir6/test2.txt'") child.close() self.assertTrue(file_exists(make_path("testdir6", "test2.txt"))) # confirm decrypted file present self.assertFalse(file_exists(make_path("testdir6", "test2.txt.tmp"))) # confirm tmp file erased
def test_multidir_bad_single_dir_path(self): command = "crypto bogusdir1 testdir2" child = self.submit_same_passphrase(command) self.assertTrue(file_exists(make_path("testdir2", "test1.txt.crypt"))) self.assertTrue(file_exists(make_path("testdir2", "test2.txt.crypt"))) self.assertFalse(file_exists(make_path("testdir2", "testcrypt.txt.crypt.crypt"))) # cleanup os.remove(make_path("testdir2","test1.txt.crypt")) os.remove(make_path("testdir2","test2.txt.crypt"))
def test_asciifile_single_directory(self): command = "crypto --armor testdir2" child = self.submit_same_passphrase(command) self.assertTrue(file_exists(make_path("testdir2", "test1.txt.crypt"))) self.assertTrue(file_exists(make_path("testdir2", "test2.txt.crypt"))) self.assertFalse( file_exists(make_path("testdir2", "testcrypt.txt.crypt.crypt")) ) # test that did not encrypt previously encrypted file child.close() # cleanup os.remove(make_path("testdir2", "test1.txt.crypt")) os.remove(make_path("testdir2", "test2.txt.crypt"))
def test_decrypt_multifile_same_directory(self): command = "decrypto testdir5/test1.txt.crypt testdir5/test2.txt.gpg testdir5/test3.txt.asc" child = self.submit_same_passphrase(command) self.assertTrue(file_exists(make_path("testdir5", "test1.txt"))) self.assertTrue(file_exists(make_path("testdir5", "test2.txt"))) self.assertTrue(file_exists(make_path("testdir5", "test3.txt"))) child.close() #cleanup os.remove(make_path("testdir5", "test1.txt")) os.remove(make_path("testdir5", "test2.txt")) os.remove(make_path("testdir5", "test3.txt"))
def setUp(self): self.cwd = os.getcwd() self.targz_pull_dir = "pull-tests/targz" self.zip_pull_dir = "pull-tests/zip" self.gzip_pull_dir = "pull-tests/gzip" self.text_pull_dir = "pull-tests/text" if dir_exists(self.targz_pull_dir): if file_exists(os.path.join(self.targz_pull_dir, 'key.yaml')): os.remove(os.path.join(self.targz_pull_dir, 'key.yaml')) if file_exists(os.path.join(self.targz_pull_dir, 'test.doxt')): os.remove(os.path.join(self.targz_pull_dir, 'test.doxt')) if file_exists(os.path.join(self.targz_pull_dir, 'test2.doxt')): os.remove(os.path.join(self.targz_pull_dir, 'test2.doxt')) if dir_exists(self.zip_pull_dir): if file_exists(os.path.join(self.zip_pull_dir, 'key.yaml')): os.remove(os.path.join(self.zip_pull_dir, 'key.yaml')) if file_exists(os.path.join(self.zip_pull_dir, 'test.doxt')): os.remove(os.path.join(self.zip_pull_dir, 'test.doxt')) if file_exists(os.path.join(self.zip_pull_dir, 'test2.doxt')): os.remove(os.path.join(self.zip_pull_dir, 'test2.doxt')) if dir_exists(self.gzip_pull_dir): if file_exists(os.path.join(self.gzip_pull_dir, 'mit.doxt')): os.remove(os.path.join(self.gzip_pull_dir, 'mit.doxt')) if dir_exists(self.text_pull_dir): if file_exists(os.path.join(self.text_pull_dir, 'mit.doxt')): os.remove(os.path.join(self.text_pull_dir, 'mit.doxt'))
def test_doxx_targz_unpack_package(self): try: os.chdir(self.targz_unpack_dir) unpack_run('unpack.tar.gz') self.assertTrue(file_exists('key.yaml')) self.assertTrue(file_exists('test.doxt')) self.assertTrue(file_exists('test2.doxt')) self.assertTrue(file_exists('unpack.tar.gz')) remove_compressed_archive_file('unpack.tar.gz') self.assertFalse(file_exists('unpack.tar.gz')) os.chdir(self.cwd) except Exception as e: os.chdir(self.cwd) raise e
def test_doxx_pull_multiple_text_files_remotefiles_module(self): try: os.chdir(self.test_dir) local_writepath_one = "testfile.txt" local_writepath_two = "testfile" pull_textfile_runner(self.test_multi_text_files_dict) self.assertTrue(file_exists(local_writepath_one)) self.assertTrue(file_exists(local_writepath_two)) os.remove(local_writepath_one) os.remove(local_writepath_two) os.chdir(self.cwd) except Exception as e: os.chdir(self.cwd) raise e
def test_decrypt_multifile_overwrite_shortflag(self): command = "decrypto -o testdir5/test1.txt.crypt testdir6/test1.txt.crypt" child = pexpect.spawn(command) child.expect("Please enter your passphrase: ") child.sendline("test") child.expect("Please enter your passphrase again: ") child.sendline("test") child.interact() child.close() self.assertTrue(file_exists(make_path("testdir5", "test1.txt"))) self.assertTrue(file_exists(make_path("testdir6", "test1.txt"))) self.assertFalse(file_exists(make_path("testdir6", "test1.txt.tmp"))) # confirm that there is no .tmp file #cleanup os.remove(make_path("testdir5", "test1.txt"))
def test_decrypt_multifile_overwrite_file(self): command = "decrypto testdir5/test1.txt.crypt testdir6/test1.txt.crypt" child = pexpect.spawn(command) child.expect("Please enter your passphrase: ") child.sendline("test") child.expect("Please enter your passphrase again: ") child.sendline("test") child.expect("The file path 'testdir6/test1.txt' already exists. This file was not decrypted") child.close() self.assertTrue(file_exists(make_path("testdir5", "test1.txt"))) self.assertTrue(file_exists(make_path("testdir6", "test1.txt"))) self.assertFalse(file_exists(make_path("testdir6", "test1.txt.tmp"))) # confirm that there is no .tmp file #cleanup os.remove(make_path("testdir5", "test1.txt"))
def _pull_archive_multiprocess(file_path, url, outputlock, iolock): """executes multi-process archive file pulls with I/O and stdout/stderr locks (private function)""" # create OS dependent file path (if necessary) file_path = _make_os_dependent_path(file_path) # make directory structure if necessary for the file path if os.path.dirname(file_path) is not "": iolock.acquire() _create_dirs(file_path) iolock.release() # pull the file and write to local filesystem try: pull_archive_file(url, file_path) except Exception as e: outputlock.acquire() stderr("[!] doxx: Unable to pull the archive file from the URL '" + url + "'. Error: " + str(e), exit=1) outputlock.release() if file_exists(file_path): root_dir = unpack_run(file_path) remove(file_path) outputlock.acquire() stdout("[+] doxx: '" + root_dir + "' ...check!") outputlock.release() else: outputlock.acquire() stderr("[!] doxx: There was an error pulling the repository file. Error: Unable to locate local archive file.", exit=1) outputlock.release()
def test_http_get_text_exists(self): """Test HTTP GET request with text file write does not overwrite existing file by default""" filepath = os.path.join('testfiles', 'keep', 'file1.txt') if not file_exists(filepath): raise RuntimeError("Missing test file for the unit test.") http = HTTP("https://raw.github.com/chrissimpkins/six-four/master/LICENSE") self.assertFalse(http.get_txt_write_file(filepath)) # should not overwrite by default
def test_mit_license_undefined_destdir_build(self): os.chdir(self.mit_test_dir) # cd to the mit test dir try: b = Builder(self.mit_key_undefined_destdir) b.run() self.assertTrue(file_exists('LICENSE')) # confirm that the rendered file write took place fr = FileReader('LICENSE') rendered_text = fr.read() self.assertEqual(self.mit_standard_text, rendered_text) # confirm that the rendered text matches expected text os.remove('LICENSE') # remove the rendered file to prepare directory for new tests os.chdir(self.current_dir) except Exception as e: if file_exists('LICENSE'): os.remove('LICENSE') # remove the generated LICENSE file if it is present before the exception was raised os.chdir(self.current_dir) # cd back to the main test directory before exception raised (avoids issues with other tests) raise e
def test_escape_passphrase_single_file_encrypt_decrypt(self): command = "crypto testdir11/esc_test.txt" child = self.submit_same_esc_passphrase(command) self.assertTrue(file_exists(make_path("testdir11", "esc_test.txt.crypt"))) # test new encrypted file exists child.close() os.rename("testdir11/esc_test.txt.crypt", "testdir11/SUBTEST.txt.crypt") decrypt_command = "decrypto testdir11/SUBTEST.txt.crypt" child = self.submit_same_esc_passphrase(decrypt_command) self.assertTrue(file_exists(make_path("testdir11", "SUBTEST.txt"))) # test decrypted file exists child.close() # cleanup os.remove(make_path("testdir11", "SUBTEST.txt")) os.remove(make_path("testdir11", "SUBTEST.txt.crypt"))
def test_http_get_binary_file_exists(self): """Test HTTP GET request and write to binary file when it does exist - should not overwrite by default""" filepath = os.path.join('testfiles', 'keep', 'test.tar.gz') if not file_exists(filepath): raise RuntimeError("Missing test file for the unit test") http = HTTP("https://github.com/chrissimpkins/six-four/tarball/master") self.assertFalse(http.get_bin_write_file(filepath)) # should not overwrite file by default
def append(self, text): try: from Naked.toolshed.system import file_exists if not file_exists( self.filepath ): #confirm that file exists, if not raise IOError (assuming that developer expected existing file if using append) raise IOError( "The file specified for the text append does not exist (Naked.toolshed.file.py:append)." ) with open(self.filepath, 'a') as appender: appender.write(text) except UnicodeEncodeError as ue: self.append_utf8(text) #try writing as utf-8 except Exception as e: if DEBUG_FLAG: sys.stderr.write( "Naked Framework Error: Unable to append text to the file with the append() method (Naked.toolshed.file.py)." ) raise e
def run(self): lib_found = False for i in range(self.number_of_dir_levels): if not self._is_lib_at_this_level(): os.chdir(os.pardir) else: lib_found = True break if lib_found: os.chdir('lib') # chdir to the lib directory if it is found if file_exists('profiler.py'): # confirm that profiler.py exists os.system('python profiler.py') # run the profiler.py file exit_success() else: stderr( "Unable to locate a profiler.py file in your lib directory.", 1) else: stderr( "Unable to locate your profiler.py file. Please navigate to your project directory.", 1)
def append_utf8(self, text): try: from Naked.toolshed.system import file_exists if not file_exists(self.filepath): raise IOError( "The file specified for the text append does not exist (Naked.toolshed.file.py:append_utf8)." ) import codecs import unicodedata norm_text = unicodedata.normalize( 'NFKD', text) # NKFD normalization of the unicode data before write with codecs.open(self.filepath, mode='a', encoding="utf_8") as appender: appender.write(norm_text) except Exception as e: if DEBUG_FLAG: sys.stderr.write( "Naked Framework Error: Unable to append text to the file with the append_utf8 method (Naked.toolshed.file.py)." ) raise e
def test_crypto_untar_overwrite_fails_without_overwrite_switch(self): shutil.copyfile(self.singlefile_encrypted_archive_sourcepath, self.singlefile_encrypted_archive_destpath) # execute first time to generate a decrypted, unpacked archive command = "decrypto testdir10/singlefile.tar.crypt" child = self.submit_same_passphrase(command) # confirm that the archive was unpacked self.assertTrue(dir_exists(os.path.join('testdir10', 'singlefile'))) self.assertTrue(file_exists(os.path.join('testdir10', 'singlefile', 'test.txt'))) child.close() # execute the command again and confirm that it raises error message, no file overwrite command = "decrypto testdir10/singlefile.tar.crypt" child = pexpect.spawn(command) child.expect("Please enter your passphrase: ") child.sendline("test") child.expect("Please enter your passphrase again: ") child.sendline("test") child.expect("Failed to unpack the file 'testdir10/singlefile/test.txt'. File already exists. Use the --overwrite flag to replace existing files.") child.close() # cleanup shutil.rmtree(os.path.join('testdir10', 'singlefile')) os.remove(os.path.join('testdir10', 'singlefile.tar.crypt'))
def test_crypto_tar_commandline_multidir_and_file(self): command = "crypto --tar testdir9/tar_dir testdir9/tar_dir_two testdir9/nontar.txt" child = pexpect.spawn(command) child.expect("Please enter your passphrase: ") child.sendline("test") child.expect("Please enter your passphrase again: ") child.sendline("test") child.expect( "\r\ntestdir9/nontar.txt.crypt was generated from testdir9/nontar.txt\r\n" ) child.expect( "testdir9/tar_dir.tar.crypt was generated from testdir9/tar_dir.tar\r\n" ) child.expect( "testdir9/tar_dir_two.tar.crypt was generated from testdir9/tar_dir_two.tar\r\n" ) self.assertTrue(file_exists(make_path('testdir9', 'tar_dir.tar.crypt')) ) # confirm that the encrypted tar file is there self.assertFalse(file_exists( make_path('testdir9', 'tar_dir.tar'))) # confirm that the tar file is removed self.assertTrue(dir_exists(make_path( 'testdir9', 'tar_dir'))) # confirm that the test directory is not removed self.assertTrue( file_exists(make_path('testdir9', 'tar_dir_two.tar.crypt')) ) # confirm that the encrypted tar file is there self.assertFalse(file_exists(make_path( 'testdir9', 'tar_dir_two.tar'))) # confirm that the tar file is removed self.assertTrue(dir_exists(make_path( 'testdir9', 'tar_dir_two'))) # confirm that the test directory is not removed self.assertTrue(file_exists(make_path('testdir9', 'nontar.txt.crypt'))) self.assertTrue(file_exists( make_path('testdir9', 'nontar.txt'))) # confirm that the file was not removed child.close() os.remove('testdir9/tar_dir.tar.crypt') os.remove('testdir9/tar_dir_two.tar.crypt') os.remove('testdir9/nontar.txt.crypt')
def setUp(self): self.pre_tardir_path = "testdir9/tar_dir" self.post_tardir_path = "testdir9/tar_dir.tar" self.pre_tardir2_path = "testdir9/tar_dir_two" self.post_tardir2_path = "testdir9/tar_dir_two.tar" self.pre_tardir_file_path = "testdir9/tar_dir/test.txt" self.pre_tardir2_file_path = "testdir9/tar_dir_two/test.txt" self.testdir_good_list = [self.pre_tardir_path] self.testdir_good_multidir_list = [ self.pre_tardir_path, self.pre_tardir2_path ] if not dir_exists(self.pre_tardir_path): stderr( "missing test directory for the CryptoTarArchiveTest in test_tar-archive.py test module", exit=1) if not file_exists(self.pre_tardir_file_path): stderr( "missing test file for the CryptoTarArchiveTest in the test_tar-archive.py test module", exit=1) if not dir_exists(self.pre_tardir2_path): stderr( "missing test directory for the CryptoTarArchiveTest in test_tar-archive.py test module", exit=1) if not file_exists(self.pre_tardir2_file_path): stderr( "missing test file for the CryptoTarArchiveTest in the test_tar-archive.py test module", exit=1) # cleanup files from old tests if still around if file_exists(self.post_tardir_path): os.remove(self.post_tardir_path) if file_exists(self.post_tardir2_path): os.remove(self.post_tardir2_path) if file_exists(self.post_tardir_path) or file_exists( self.post_tardir2_path): stderr( "unable to delete testfile in setup for CryptoTarArchiveTest in the test_tar-archive.py test module", exit=1)
def test_sys_file_exists(self): """Test for existence of a file that exists""" filepath = make_path("testfiles", "testdir", "systest.txt") self.assertEqual(True, system.file_exists(filepath))
def _is_setup_py_at_this_level(self): if file_exists('setup.py'): return True else: return False
def setUp(self): self.cwd = os.getcwd() self.testdir = 'testdir10' self.sourcedir = os.path.join(self.testdir, 'sourcedir') self.nofile_encrypted_archive_sourcepath = os.path.join(self.sourcedir, 'nofile.tar.crypt') self.nofile_encrypted_archive_destpath = os.path.join(self.testdir, 'nofile.tar.crypt') self.singlefile_encrypted_archive_sourcepath = os.path.join(self.sourcedir, 'singlefile.tar.crypt') self.singlefile_encrypted_archive_destpath = os.path.join(self.testdir, 'singlefile.tar.crypt') self.multifile_encrypted_archive_sourcepath = os.path.join(self.sourcedir, 'multifile.tar.crypt') self.multifile_encrypted_archive_destpath = os.path.join(self.testdir, 'multifile.tar.crypt') self.subdirs_encrypted_archive_sourcepath = os.path.join(self.sourcedir, 'subdirs.tar.crypt') self.subdirs_encrypted_archive_destpath = os.path.join(self.testdir, 'subdirs.tar.crypt') # cleanup old test files if they are present if file_exists(self.nofile_encrypted_archive_destpath): os.remove(self.nofile_encrypted_archive_destpath) if file_exists(self.singlefile_encrypted_archive_destpath): os.remove(self.singlefile_encrypted_archive_destpath) if file_exists(self.multifile_encrypted_archive_destpath): os.remove(self.multifile_encrypted_archive_destpath) if file_exists(self.subdirs_encrypted_archive_destpath): os.remove(self.subdirs_encrypted_archive_destpath) if file_exists(os.path.join(self.testdir, 'nofile.tar')): os.remove(os.path.join(self.testdir, 'nofile.tar')) if file_exists(os.path.join(self.testdir, 'nofile.tar.crypt')): os.remove(os.path.join(self.testdir, 'nofile.tar.crypt')) if dir_exists(os.path.join(self.testdir, 'nofile')): shutil.rmtree(os.path.join(self.testdir, 'nofile')) if file_exists(os.path.join(self.testdir, 'singlefile.tar')): os.remove(os.path.join(self.testdir, 'singlefile.tar')) if file_exists(os.path.join(self.testdir, 'singlefile.tar.crypt')): os.remove(os.path.join(self.testdir, 'singlefile.tar.crypt')) if dir_exists(os.path.join(self.testdir, 'singlefile')): shutil.rmtree(os.path.join(self.testdir, 'singlefile')) if file_exists(os.path.join(self.testdir, 'multifile.tar')): os.remove(os.path.join(self.testdir, 'multifile.tar')) if file_exists(os.path.join(self.testdir, 'multifile.tar.crypt')): os.remove(os.path.join(self.testdir, 'multifile.tar.crypt')) if dir_exists(os.path.join(self.testdir, 'multifile')): shutil.rmtree(os.path.join(self.testdir, 'multifile')) if file_exists(os.path.join(self.testdir, 'subdirs.tar')): os.remove(os.path.join(self.testdir, 'subdirs.tar')) if file_exists(os.path.join(self.testdir, 'subdirs.tar.crypt')): os.remove(os.path.join(self.testdir, 'subdirs.tar.crypt')) if dir_exists(os.path.join(self.testdir, 'subdirs')): shutil.rmtree(os.path.join(self.testdir, 'subdirs'))
def _is_tox_ini_at_this_level(self): if file_exists('tox.ini'): return True else: return False
def test_sys_file_exists_missing_file(self): """Test for existence of a file that does not exist""" self.assertEqual(False, system.file_exists(self.bogusfilepath))
def main(): import os import sys from time import sleep import getpass import tarfile from Naked.commandline import Command from Naked.toolshed.shell import execute, muterun from Naked.toolshed.system import dir_exists, file_exists, list_all_files, make_path, stdout, stderr, is_dir from shellescape import quote # ------------------------------------------------------------------------------------------ # [ Instantiate command line object ] # used for all subsequent conditional logic in the CLI application # ------------------------------------------------------------------------------------------ c = Command(sys.argv[0], sys.argv[1:]) # ------------------------------------------------------------------------------------------ # [ VALIDATION LOGIC ] - early validation of appropriate command syntax # Test that user entered at least one argument to the executable, print usage if not # ------------------------------------------------------------------------------------------ if not c.command_suite_validates(): from Crypto.settings import usage as crypto_usage print(crypto_usage) sys.exit(1) # ------------------------------------------------------------------------------------------ # [ HELP, VERSION, USAGE LOGIC ] # Naked framework provides default help, usage, and version commands for all applications # --> settings for user messages are assigned in the lib/Crypto/settings.py file # ------------------------------------------------------------------------------------------ if c.help(): # User requested Crypto help information from Crypto.settings import help as crypto_help print(crypto_help) sys.exit(0) elif c.usage(): # User requested Crypto usage information from Crypto.settings import usage as crypto_usage print(crypto_usage) sys.exit(0) elif c.version(): # User requested Crypto version information from Crypto.settings import app_name, major_version, minor_version, patch_version version_display_string = app_name + ' ' + major_version + '.' + minor_version + '.' + patch_version print(version_display_string) sys.exit(0) # ------------------------------------------------------------------------------------------ # [ APPLICATION LOGIC ] # # ------------------------------------------------------------------------------------------ elif c.argc > 1: # code for multi-file processing and commands that include options use_standard_output = False # print to stdout flag use_file_overwrite = False # overwrite existing file untar_archives = True # untar decrypted tar archives, true by default # set user option flags if c.option('--stdout') or c.option('-s'): use_standard_output = True if c.option('--overwrite') or c.option('-o'): use_file_overwrite = True if c.option('--nountar'): untar_archives = False directory_list = [ ] # directory paths included in the user entered paths from the command line file_list = [ ] # file paths included in the user entered paths from the command line (and inside directories entered) for argument in c.argv: if file_exists( argument ): # user included a file, add it to the file_list for decryption if argument.endswith('.crypt'): file_list.append( argument ) # add .crypt files to the list of files for decryption elif argument.endswith('.gpg'): file_list.append(argument) elif argument.endswith('.asc'): file_list.append(argument) elif argument.endswith('.pgp'): file_list.append(argument) else: # cannot identify as an encrypted file, give it a shot anyways but warn user file_list.append(argument) stdout( "Could not confirm that '" + argument + "' is encrypted based upon the file type. Attempting decryption. Keep your fingers crossed..." ) elif dir_exists( argument ): # user included a directory, add it to the directory_list directory_list.append(argument) else: if argument[0] == "-": pass # if it is an option, do nothing else: stderr( "'" + argument + "' does not appear to be an existing file or directory. Aborting decryption attempt for this request." ) # unroll the contained directory files into the file_list IF they are encrypted file types if len(directory_list) > 0: for directory in directory_list: directory_file_list = list_all_files(directory) for contained_file in directory_file_list: if contained_file.endswith('.crypt'): file_list.append( make_path(directory, contained_file) ) # include the file with a filepath 'directory path/contained_file path' elif contained_file.endswith('.gpg'): file_list.append(make_path(directory, contained_file)) elif contained_file.endswith('asc'): file_list.append(make_path(directory, contained_file)) elif contained_file.endswith('.pgp'): file_list.append(make_path(directory, contained_file)) # confirm that there are files for decryption, if not abort if len(file_list) == 0: stderr("Could not identify files for decryption") sys.exit(1) # get passphrase used to symmetrically decrypt the file passphrase = getpass.getpass("Please enter your passphrase: ") if len(passphrase) == 0: # confirm that user entered a passphrase stderr( "You did not enter a passphrase. Please repeat your command and try again." ) sys.exit(1) passphrase_confirm = getpass.getpass( "Please enter your passphrase again: ") if passphrase == passphrase_confirm: # begin decryption of each requested file. the directory path was already added to the file path above for encrypted_file in file_list: # create the decrypted file name decrypted_filename = "" if encrypted_file.endswith('.crypt'): decrypted_filename = encrypted_file[0:-6] elif encrypted_file.endswith( '.gpg') or encrypted_file.endswith( '.asc') or encrypted_file.endswith('.pgp'): decrypted_filename = encrypted_file[0:-4] else: decrypted_filename = encrypted_file + '.decrypt' # if it was a file without a known encrypted file type, add the .decrypt suffix # determine whether file overwrite will take place with the decrypted file skip_file = False # flag that indicates this file should not be encrypted created_tmp_files = False if not use_standard_output: # if not writing a file, no need to check for overwrite if file_exists(decrypted_filename): if use_file_overwrite: # rename the existing file to temp file which will be erased or replaced (on decryption failures) below tmp_filename = decrypted_filename + '.tmp' os.rename(decrypted_filename, tmp_filename) created_tmp_files = True else: stdout( "The file path '" + decrypted_filename + "' already exists. This file was not decrypted." ) skip_file = True # begin decryption if not skip_file: if use_standard_output: # using --quiet flag to suppress stdout messages from gpg, just want the file data in stdout stream system_command = "gpg --batch --quiet --passphrase " + quote( passphrase) + " -d " + quote(encrypted_file) successful_execution = execute( system_command ) # use naked execute function to directly push to stdout, rather than return stdout if not successful_execution: stderr( "Unable to decrypt file '" + encrypted_file + "'", 0) if created_tmp_files: # restore the moved tmp file to original if decrypt failed tmp_filename = decrypted_filename + '.tmp' if file_exists(tmp_filename): os.rename(tmp_filename, decrypted_filename) else: # decryption successful but we are in stdout flag so do not include any other output from decrypto pass else: system_command = "gpg --batch -o " + quote( decrypted_filename) + " --passphrase " + quote( passphrase) + " -d " + quote(encrypted_file) response = muterun(system_command) if response.exitcode == 0: stdout("'" + encrypted_file + "' decrypted to '" + decrypted_filename + "'") else: # failed decryption if created_tmp_files: # restore the moved tmp file to original if decrypt failed tmp_filename = decrypted_filename + '.tmp' if file_exists(tmp_filename): os.rename(tmp_filename, decrypted_filename) # report the error stderr(response.stderr) stderr("Decryption failed for " + encrypted_file) # cleanup: remove the tmp file if created_tmp_files: tmp_filename = decrypted_filename + '.tmp' if file_exists(tmp_filename): os.remove(tmp_filename) # untar/extract any detected archive file(s) if untar_archives is True: if decrypted_filename.endswith( '.tar') and tarfile.is_tarfile(decrypted_filename): untar_path_tuple = os.path.split(decrypted_filename) untar_path = untar_path_tuple[0] if use_file_overwrite: with tarfile.open(decrypted_filename) as tar: if len(untar_path) > 0: tar.extractall( path=untar_path ) # use dir path from the decrypted_filename if not CWD stdout( "'" + decrypted_filename + "' unpacked in the directory path '" + untar_path + "'") else: tar.extractall() # else use CWD stdout( "'" + decrypted_filename + "' unpacked in the current working directory" ) else: with tarfile.TarFile(decrypted_filename, 'r', errorlevel=1) as tar: for tarinfo in tar: t_file = tarinfo.name if len(untar_path) > 0: t_file_path = os.path.join( untar_path, t_file) else: t_file_path = t_file if not os.path.exists(t_file_path): try: if len(untar_path) > 0: tar.extract( t_file, path=untar_path ) # write to the appropriate dir else: tar.extract( t_file) # write to CWD except IOError as e: stderr( "Failed to unpack the file '" + t_file_path + "' [" + str(e) + "]") elif is_dir(t_file_path): pass # do nothing if it exists and is a directory, no need to warn else: # it is a file and it already exists, provide user error message stderr( "Failed to unpack the file '" + t_file_path + "'. File already exists. Use the --overwrite flag to replace existing files." ) # remove the decrypted tar archive file os.remove(decrypted_filename) # overwrite the entered passphrases after file decryption is complete for all files passphrase = "" passphrase_confirm = "" # add a short pause to hinder brute force pexpect style password attacks with decrypto sleep(0.2) # 200ms pause else: # passphrases did not match passphrase = "" passphrase_confirm = "" stderr( "The passphrases did not match. Please enter your command again." ) sys.exit(1) elif c.argc == 1: # simple single file or directory processing with default settings path = c.arg0 if file_exists(path): # SINGLE FILE check_existing_file = False # check for a file with the name of new decrypted filename in the directory if path.endswith('.crypt'): decrypted_filename = path[0:-6] # remove the .crypt suffix check_existing_file = True elif path.endswith('.gpg') or path.endswith( '.pgp') or path.endswith('.asc'): decrypted_filename = path[0:-4] check_existing_file = True else: decrypted_filename = path + ".decrypt" # if there is not a standard file type, then add a .decrypt suffix to the decrypted file name stdout( "Could not confirm that the requested file is encrypted based upon the file type. Attempting decryption. Keep your fingers crossed..." ) # confirm that the decrypted path does not already exist, if so abort with warning message to user if check_existing_file is True: if file_exists(decrypted_filename): stderr( "Your file will be decrypted to '" + decrypted_filename + "' and this file path already exists. Please move the file or use the --overwrite option with your command if you intend to replace the current file." ) sys.exit(1) # get passphrase used to symmetrically decrypt the file passphrase = getpass.getpass("Please enter your passphrase: ") if len(passphrase) == 0: # confirm that user entered a passphrase stderr( "You did not enter a passphrase. Please repeat your command and try again." ) sys.exit(1) passphrase_confirm = getpass.getpass( "Please enter your passphrase again: ") # confirm that the passphrases match if passphrase == passphrase_confirm: system_command = "gpg --batch -o " + quote( decrypted_filename) + " --passphrase " + quote( passphrase) + " -d " + quote(path) response = muterun(system_command) if response.exitcode == 0: # unpack tar archive generated from the decryption, if present if decrypted_filename.endswith( '.tar') and tarfile.is_tarfile(decrypted_filename): untar_path_tuple = os.path.split(decrypted_filename) untar_path = untar_path_tuple[0] with tarfile.TarFile(decrypted_filename, 'r', errorlevel=1) as tar: for tarinfo in tar: t_file = tarinfo.name if len(untar_path) > 0: t_file_path = os.path.join( untar_path, t_file) else: t_file_path = t_file if not os.path.exists(t_file_path): try: if len(untar_path) > 0: tar.extract( t_file, path=untar_path ) # write to the appropriate dir else: tar.extract(t_file) # write to CWD except IOError as e: stderr("Failed to unpack the file '" + t_file_path + "' [" + str(e) + "]") elif is_dir(t_file_path): pass # do nothing if it exists and is a directory, no need to warn else: # it is a file and it already exists, provide user error message stderr( "Failed to unpack the file '" + t_file_path + "'. File already exists. Use the --overwrite flag to replace existing files." ) # remove the decrypted tar archive os.remove(decrypted_filename) stdout("Decryption complete") # overwrite user entered passphrases passphrase = "" passphrase_confirm = "" sys.exit(0) else: stderr(response.stderr) stderr("Decryption failed") # overwrite user entered passphrases passphrase = "" passphrase_confirm = "" # add a short pause to hinder brute force pexpect style password attacks with decrypto sleep(0.2) # 200ms pause sys.exit(1) else: stderr( "The passphrases did not match. Please enter your command again." ) sys.exit(1) elif dir_exists(path): # SINGLE DIRECTORY dirty_directory_file_list = list_all_files(path) directory_file_list = [ x for x in dirty_directory_file_list if (x.endswith('.crypt') or x.endswith('.gpg') or x.endswith('.pgp') or x.endswith('.asc')) ] # if there are no encrypted files found, warn and abort if len(directory_file_list) == 0: stderr("There are no encrypted files in the directory") sys.exit(1) # prompt for the passphrase passphrase = getpass.getpass("Please enter your passphrase: ") if len(passphrase) == 0: # confirm that user entered a passphrase stderr( "You did not enter a passphrase. Please repeat your command and try again." ) sys.exit(1) passphrase_confirm = getpass.getpass( "Please enter your passphrase again: ") if passphrase == passphrase_confirm: # decrypt all of the encypted files in the directory for filepath in directory_file_list: absolute_filepath = make_path( path, filepath ) # combine the directory path and file name into absolute path # remove file suffix from the decrypted file path that writes to disk if absolute_filepath.endswith('.crypt'): decrypted_filepath = absolute_filepath[ 0:-6] # remove the .crypt suffix elif absolute_filepath.endswith( '.gpg') or absolute_filepath.endswith( '.pgp') or absolute_filepath.endswith('.asc'): decrypted_filepath = absolute_filepath[0:-4] # confirm that the file does not already exist if file_exists(decrypted_filepath): stdout( "The file path '" + decrypted_filepath + "' already exists. This file was not decrypted.") else: system_command = "gpg --batch -o " + quote( decrypted_filepath) + " --passphrase " + quote( passphrase) + " -d " + quote(absolute_filepath) response = muterun(system_command) if response.exitcode == 0: stdout("'" + absolute_filepath + "' decrypted to '" + decrypted_filepath + "'") else: stderr(response.stderr) stderr("Decryption failed for " + absolute_filepath) # overwrite user entered passphrases passphrase = "" passphrase_confirm = "" # add a short pause to hinder brute force pexpect style password attacks with decrypto sleep(0.2) # 200ms pause else: # overwrite user entered passphrases passphrase = "" passphrase_confirm = "" stderr( "The passphrases did not match. Please enter your command again." ) sys.exit(1) else: # error message, not a file or directory. user entry error stderr( "The path that you entered does not appear to be an existing file or directory. Please try again." ) sys.exit(1) # ------------------------------------------------------------------------------------------ # [ DEFAULT MESSAGE FOR MATCH FAILURE ] # Message to provide to the user when all above conditional logic fails to meet a true condition # ------------------------------------------------------------------------------------------ else: print("Could not complete your request. Please try again.") sys.exit(1)
def main(): import sys import getpass from Naked.commandline import Command from Naked.toolshed.shell import muterun from Naked.toolshed.system import dir_exists, directory, filename, file_exists, list_all_files, make_path, stdout, stderr #------------------------------------------------------------------------------------------ # [ Instantiate command line object ] # used for all subsequent conditional logic in the CLI application #------------------------------------------------------------------------------------------ c = Command(sys.argv[0], sys.argv[1:]) #------------------------------------------------------------------------------------------ # [ VALIDATION LOGIC ] - early validation of appropriate command syntax # Test that user entered at least one argument to the executable, print usage if not #------------------------------------------------------------------------------------------ if not c.command_suite_validates(): from crypto.settings import usage as crypto_usage print(crypto_usage) sys.exit(1) #------------------------------------------------------------------------------------------ # [ HELP, VERSION, USAGE LOGIC ] # Naked framework provides default help, usage, and version commands for all applications # --> settings for user messages are assigned in the lib/crypto/settings.py file #------------------------------------------------------------------------------------------ if c.help(): # User requested crypto help information from crypto.settings import help as crypto_help print(crypto_help) sys.exit(0) elif c.usage(): # User requested crypto usage information from crypto.settings import usage as crypto_usage print(crypto_usage) sys.exit(0) elif c.version(): # User requested crypto version information from crypto.settings import app_name, major_version, minor_version, patch_version version_display_string = app_name + ' ' + major_version + '.' + minor_version + '.' + patch_version print(version_display_string) sys.exit(0) #------------------------------------------------------------------------------------------ # [ APPLICATION LOGIC ] # #------------------------------------------------------------------------------------------ elif c.argc > 1: # code for multi-file processing and commands that include options ## ASCII ARMOR SWITCH ascii_armored = False if c.option('--armor') or c.option('-a'): ascii_armored = True ## MAX COMPRESS / COMPRESS ALL SWITCH max_compress = False if c.option('--space'): max_compress = True ## NO COMPRESSION SWITCH no_compress = False if c.option('--speed'): no_compress = True ## SECURE HASH DIGEST REPORT SWITCH report_checksum = False if c.option('--hash'): report_checksum = True path_list = [] # user entered paths from command line directory_list = [ ] # directory paths included in the user entered paths from the command line file_list = [ ] # file paths included in the user entered paths from the command line (and inside directories entered) # dot and .crypt file flags for exclusion testing contained_dot_file = False contained_crypt_file = False # determine if argument is an existing file or directory for argument in c.argv: if file_exists(argument): if argument.endswith( '.crypt'): # do not include previously encrypted files contained_crypt_file = True else: file_list.append( argument ) # add appropriate file paths to the file_list elif dir_exists(argument): directory_list.append( argument ) # if it is a directory, add path to the directory_list # add all file paths from user specified directories to the file_list if len(directory_list) > 0: for directory in directory_list: directory_file_list = list_all_files(directory) for contained_file in directory_file_list: if contained_file[0] == ".": contained_dot_file = True # change the flag + is not included in file_list intentionally (no dot files) elif contained_file.endswith('.crypt'): contained_crypt_file = True # change the flag + is not included in file_list intentionally (no previously encrypted files) else: # otherwise add to the list for encryption contained_file_path = make_path( directory, contained_file) file_list.append(contained_file_path) # confirm that there are files to be encrypted, if not warn user if len(file_list) == 0: if contained_dot_file == True or contained_crypt_file == True: stderr( "There were no files identified for encryption. crypto does not encrypt dot files or previously encrypted '.crypt' files." ) sys.exit(1) else: stderr("Unable to identify files for encryption") sys.exit(1) else: # file_list should contain all filepaths from either user specified file paths or contained in top level of directory, encrypt them passphrase = getpass.getpass("Please enter your passphrase: ") if len(passphrase) == 0: # confirm that user entered a passphrase stderr( "You did not enter a passphrase. Please repeat your command and try again." ) sys.exit(1) passphrase_confirm = getpass.getpass( "Please enter your passphrase again: ") if passphrase == passphrase_confirm: from crypto.library.cryptor import Cryptor the_cryptor = Cryptor(passphrase) # run encryption based upon any passed switches if ascii_armored: if max_compress: the_cryptor.encrypt_files(file_list, force_nocompress=False, force_compress=True, armored=True, checksum=report_checksum) elif no_compress: the_cryptor.encrypt_files(file_list, force_nocompress=True, force_compress=False, armored=True, checksum=report_checksum) else: the_cryptor.encrypt_files(file_list, force_nocompress=False, force_compress=False, armored=True, checksum=report_checksum) else: if max_compress: the_cryptor.encrypt_files(file_list, force_nocompress=False, force_compress=True, armored=False, checksum=report_checksum) elif no_compress: the_cryptor.encrypt_files(file_list, force_nocompress=True, force_compress=False, armored=False, checksum=report_checksum) else: the_cryptor.encrypt_files(file_list, force_nocompress=False, force_compress=False, armored=False, checksum=report_checksum) # overwrite user entered passphrases passphrase = "" passphrase_confirm = "" the_cryptor.cleanup() else: # passphrases did not match, report to user and abort # overwrite user entered passphrases passphrase = "" passphrase_confirm = "" stderr( "The passphrases did not match. Please enter your command again." ) sys.exit(1) elif c.argc == 1: # simple single file or directory processing with default settings path = c.arg0 if file_exists(path): # it is a file, encrypt the single file with default settings # confirm that it is not already encrypted, abort if so if path.endswith('.crypt'): stderr( "You are attempting to encrypt an encrypted file. Please delete the .crypt file and repeat encryption with the original file if this is your intent." ) sys.exit(1) # if passes test above, obtain passphrase from the user passphrase = getpass.getpass("Please enter your passphrase: ") if len(passphrase) == 0: # confirm that user entered a passphrase stderr( "You did not enter a passphrase. Please repeat your command and try again." ) sys.exit(1) passphrase_confirm = getpass.getpass( "Please enter your passphrase again: ") if passphrase == passphrase_confirm: from crypto.library.cryptor import Cryptor the_cryptor = Cryptor(passphrase) the_cryptor.encrypt_file(path) the_cryptor.cleanup() else: stderr( "The passphrases did not match. Please enter your command again." ) sys.exit(1) elif dir_exists(path): # it is a directory, encrypt all top level files with default settings dirty_directory_file_list = list_all_files(path) # remove dot files and previously encrypted files (with .crypt suffix) from the list of directory files clean_directory_file_list = [ x for x in dirty_directory_file_list if x[0] != "." and x.endswith(".crypt") == False ] # remove dotfiles and .crypt files # confirm that there are still files in the list after the dot files and encrypted files are removed if len(clean_directory_file_list) == 0: stderr("There are no unencrypted files in the directory.") sys.exit(1) # create relative file paths for each file in the clean_directory_file_list clean_directory_file_list_relpaths = [] for clean_file in clean_directory_file_list: new_file_path = make_path(path, clean_file) clean_directory_file_list_relpaths.append(new_file_path) #prompt for the passphrase passphrase = getpass.getpass("Please enter your passphrase: ") if len(passphrase) == 0: # confirm that user entered a passphrase stderr( "You did not enter a passphrase. Please repeat your command and try again." ) sys.exit(1) passphrase_confirm = getpass.getpass( "Please enter your passphrase again: ") if passphrase == passphrase_confirm: from crypto.library.cryptor import Cryptor the_cryptor = Cryptor(passphrase) the_cryptor.encrypt_files( clean_directory_file_list_relpaths ) #encrypt the list of directory files the_cryptor.cleanup() else: # passphrases do not match # overwrite user entered passphrases passphrase = "" passphrase_confirm = "" stderr( "The passphrases did not match. Please enter your command again." ) sys.exit(1) else: # error message, not a file or directory. user entry error stderr( "The path that you entered does not appear to be an existing file or directory. Please try again." ) sys.exit(1) #------------------------------------------------------------------------------------------ # [ DEFAULT MESSAGE FOR MATCH FAILURE ] # Message to provide to the user when all above conditional logic fails to meet a true condition #------------------------------------------------------------------------------------------ else: print("Could not complete your request. Please try again.") sys.exit(1)