- Simplest way to password protect a directory and its contents without having to create new files?
- 2 Answers 2
- How to Password Protect a Folder in Linux
- Password protect folders in Linux
- Method 1: Lock folders with Gnome EncFS Manager
- Method 2: Lock files with VeraCrypt
- Private or not?
- Где хранятся пароли пользователей Linux
Simplest way to password protect a directory and its contents without having to create new files?
I would like to password protect or encrypt a directory and all the files within it (for the whole directory tree below it). I do not want to bother the whole home directory, I want a specific directory with some files and folders in it. I would like to be able to encrypt the directory or decrypt it using a password. Command line would be nicest to use. I don’t want to have to create a new file as an encrypted version and then, delete the previous ones which are the non-encrypted version.
@Vass The filesystem route is the simplest method by far. You’ll make your life easier if you don’t reject solutions arbitrarily.
2 Answers 2
Use encfs (available as a package on most distributions). To set up:
mkdir ~/.encrypted ~/encrypted encfs ~/.encrypted ~/encrypted # enter a passphrase mv existing-directory ~/encrypted
The initial call to encfs sets up an encrypted filesystem. After that point, every file that you write under ~/encrypted is not stored directly on the disk, it is encrypted and the encrypted data is stored under ~/.encrypted . The encfs command leaves a daemon running, and this daemon handles the encryption (and decryption when you read a file from under ~/encrypted ).
In other words, for files under ~/encrypted , actions such as reads and writes do not translate directly to reading or writing from the disk. They are performed by the encfs process, which encrypts and decrypts the data and uses the ~/.encrypted directory to store the ciphertext.
When you’ve finished working with your files for the time being, unmount the filesystem so that the data can’t be accessed until you type your passphrase again:
After that point, ~/encrypted will be an empty directory again.
When you later want to work on these files again, mount the encrypted filesystem:
encfs ~/.encrypted ~/encrypted # enter your passphrase
This, again, makes the encrypted files in ~/.encrypted accessible under the directory ~/encrypted .
You can change the mount point ~/encrypted as you like: encfs ~/.encrypted /somewhere/else (but mount the encrypted directory only once at a time). You can copy or move the ciphertext (but not while it’s mounted) to a different location or even to a different machine; all you need to do to work on the files is pass the location of the ciphertext as the first argument to encfs and the location of an empty directory as the second argument.
How to Password Protect a Folder in Linux
Got some special files to save from prying eyes? Learn how to create password protected folders in the Linux desktop.
In a situation where you often share your computer with others but have some private files that you don’t want others to see? You can try hiding it in places where others cannot find it. Like in a deeply nested folder structure but that’s not entirely foolproof because the files could be shown in the desktop search results. On Android, there are several applications to lock gallery photos or hide them. I haven’t used such folder-locking applications in Linux. My laptop is used only by me and I do not need to hide any files. If so, then why are we talking about folder lock for Linux today? I got a request from an It’s FOSS reader for a tutorial on encrypted folders in Ubuntu. If this interests you, let’s see how to lock a folder in Linux.
Password protect folders in Linux
The tools discussed here do not give you military-grade encryption. But for average desktop users, they should work just fine.
I am using Ubuntu in this tutorial but you can use any other Linux distribution based on Ubuntu such as Linux Mint, elementary OS, etc. The steps should apply to other Linux distributions such as Fedora, Arch Linux, etc but the commands to install the tool won’t be the same.
Method 1: Lock folders with Gnome EncFS Manager
Let’s see how to install Gnome Encfs Manager.
If you are using Ubuntu or Linux Mint or other Linux distributions based on Ubuntu, you can use the official PPA using the commands below one by one:
sudo add-apt-repository ppa:gencfsm sudo apt update sudo apt install gnome-encfs-manager
Packages for Debian, Fedora, and OpenSUSE are available here.
If you are using GNOME on Wayland and don’t have the system tray app indicator support, you should use this GNOME extension to add quick access to the top panel. Read this article to learn how to use GNOME extensions.
Once installed, you may have to log out to see the application working. Now, go to the application menu and start Gnome Encfs Manager. On the first opening, it will show you a warning message about the existing vulnerability. You need to press Enter on OK to continue.
Now, click on the + sign to add a new folder that you’ll be locking with a password. A password-protected folder is called stash in this application’s terminology.
Here, you can create a new directory or browse an existing one. You can try password-protect an existing folder, but the files already in the folder won’t be locked. For this reason, I suggest creating a new folder and moving the files after you password-protect it.
Don’t forget to use a password that you will remember easily. If you forget the password, you should also forget the files locked with it.
Once the folder is created, you can start copying the files into it. Your locked folder will be seen as a mounted drive when you have unlocked it.
You can get control of the locked folder from the GNOME extension. I am not sure if other desktop environments have anything similar. I leave that to your exploration.
Once you have copied the files into the secret folder, simply unmount it. You can do that by unchecking the mounted folder from the panel extension as shown above. When you want to access it, use the launcher in the top panel or start the program again.
You can also use advanced settings such as auto-start or auto-unmount after a certain idle time.
Note that the so-called secret directory will be visible and accessible to anyone in its usual location. However, its content won’t be in a readable format, not even the filenames.
When you mount the locked folder, it will become readable.
That’s all you need to know about password-protecting folders with Gnome Encfs Manager.
Method 2: Lock files with VeraCrypt
VeraCrypt is a free, open-source disk encryption software, available for all major platforms, and is based on TrueCrypt 7.1a.
It is available as a deb package for Ubuntu releases up to 22.04. It also offers several installation packages for various recent versions of Fedora, Debian, OpenSUSE, etc. You need to download the appropriate file from their official downloads page.
Once downloaded the file, install the deb file in Ubuntu using the terminal, software center, or GDebi package installer, according to your choice.
After installation, open VeraCrypt from the Ubuntu Activities overview.
Now, select a slot (64 by default) and click on create volume button.
Select the Create an encrypted file container option on the next screen and click Next.
After that, select the Standard VeraCrypt volume as the Volume Type and press Next.
This will lead you to a window, where, you want to select a file to store the encrypted volume. You need to press the Select File option.
This will open the file explorer window and you can create a new file by typing a name on the top name bar as shown below and pressing Save.
If you select any existing file, the process still works. It won’t encrypt that existing file but replace that file with a new one, leading to loss of content. So better create a new file for this purpose.
Once the file is selected, in the next step, you need to specify the Encryption type, that is the Encryption and Hash algorithm. The default is AES and SHA-512. Press Next.
Now, give a size for the encrypted volume. Here, allocate a size that will satisfy your need.
Following the above step, you must provide a password for the encryption. VeraCrypt suggests (not mandatory) a 20+ character password; they will prompt this if not satisfied.
In the Next step, choose the filesystem for the volume. Several options are available including NTFS. After selecting, press Next.
The last page will ask you to randomly move your mouse inside the window to increase encryption strength. Do it till the progress bar reaches the other end :). Now press Format.
Now, you can press Exit to finish the process.
Once the volume is created, you need to mount this. To do that, open VeraCrypt and select Select File.
Choose the file you created initially and press Mount to mount the volume.
This will ask you for the encryption password. Also, you may be asked for your user password in this process. Give them.
Now, you can paste the files you want to encrypt inside this volume. Upon unmounting, you need the password to reaccess it. Keep in mind the size of the volume you allotted to it at the beginning; this will be the copying limit.
Note that, VeraCrypt won’t be started automatically at each boot. If you want that, read this guide to manage start up applications in Ubuntu and see how can you start VeraCrypt at each boot.
Private or not?
Enjoy your private locked folder in Linux. As I mentioned earlier, it gives you some basic functionality where an average person cannot access the files you have kept in the locked folder.
For better security, you should encrypt the entire disk while installing the operating system. Most people don’t need security at such a level.
Questions or suggestions are always welcome.
Где хранятся пароли пользователей Linux
В Linux нет особого реестра, где бы хранились настройки программ, данные пользователей и другие компоненты системы. Всё хранится в файлах. В этой небольшой статье мы поговорим о том, где хранятся пароли пользователей Linux.
Изначально для хранения паролей использовался файл /etc/passwd. Но этот файл доступен для чтения всем пользователям. Поэтому, из соображений безопасности, пароли пользователей были перенесены в файл /etc/shadow. Этот файл доступен для чтения только пользователю root.
Важно отметить, что пароли в этом файле хранятся не в открытом виде, а в хэшированном. Существует несколько алгоритмов хэширования паролей для Linux. Подробно всё это рассматривалось в статье про смену пароля Linux. Сейчас же давайте посмотрим на общий синтаксис файла /etc/shadow:
В первой строке представлены следующие данные:
- root — имя пользователя, для которого сохранен пароль;
- $6$yr. — хэш пароля, длина хэша от пароля никак не зависит, в данном случае зашифровано слово password;
- 18376 — дата последнего изменения пароля;
- 0 — количество дней на смену пароля, если его срок действия истёк;
- 999999 — количество дней от момента последней смены пароля до момента, когда надо сменить пароль принудительно;
- 7 — за сколько дней пользователь будет предупреждён о необходимости смены пароля.
- Ещё три поля — задают параметры отключения учётной записи пользователя.
Это всё, что следует знать об этом файле. В Linux есть ещё одно место, где приложения хранят свои пароли, SSH-ключи и другие секретные данные. Это хранилище ключей. В Gnome утилита называется SeaHorce. Вы можете найти её по названию в главном меню:
В самой утилите вы сможете найти и удалить ключи от различных приложений, ключ от хранилища паролей Chromium, токен доступа в Skype, а также все SSH-ключи, добавленные к вашей системе.
Естественно, здесь всё тоже захэшировано и просто прочитать пароль не получиться, если, конечно, какое-нибудь приложение не хранит их в открытом виде. Теперь вы знаете, где хранятся пароли в Linux. На этом всё.
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.