How to protect the password for YBDB in a public environment.

PROTECTING A DIRECTORY UNDER A WEBSERVER (apache 2.4)

A. The htpasswd command is found in the apache2-utils package.

B. htpasswd  -Bc -C 10 htpasswd test  (note that bcrypt is used)

C.  chown www-data:www-data /var/htpasswd; chmod 0400 /var/htpasswd; \

D.   In associated virtual host file, e.g. default-ssl.conf:
		<Directory /var/www/html>
            Authtype        Basic
            Authname        "Amazing Community Bike Shop Login"
            Require         user someuser
            AuthUserFile    /var/htpasswd
     </Directory>

SSL (do not settle for anything less)

- SELF-SIGNED
Under Debian (updated for Chrome 58 or greater):

I.
openssl genrsa -out rootCA.key 2048
openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 36500 -out rootCA.pem

create this file - v3.ext:
		authorityKeyIdentifier=keyid,issuer
		basicConstraints=CA:FALSE
		keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
		subjectAltName = @alt_names
		
		[alt_names]
		DNS.1 = %%DOMAIN%%

Run this script in same directory as v3.ext file:
		if [ -z "$1" ]
		then
		  echo "Please supply a domain to create a certificate for";
		  echo "e.g. mysite.com"
		  exit;
		fi
		
		# Create a new private key if one doesnt exist, or use the existing one if it does
		if [ -f device.key ]; then
		  KEY_OPT="-key"
		else
		  KEY_OPT="-keyout"
		fi
		
		DOMAIN=$1
		COMMON_NAME=${2:-*.$1}
		SUBJECT="/C=CA/ST=None/L=NB/O=None/CN=$COMMON_NAME"
		NUM_OF_DAYS=36500
		openssl req -new -newkey rsa:2048 -sha256 -nodes $KEY_OPT device.key -subj "$SUBJECT" -out device.csr
		cat v3.ext | sed s/%%DOMAIN%%/$COMMON_NAME/g > /tmp/__v3.ext
		openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days $NUM_OF_DAYS -sha256 -extfile /tmp/__v3.ext 
		
		# move output files to final filenames
		mv device.csr $DOMAIN.csr
		cp device.crt $DOMAIN.crt
		
		# remove temp file
		rm -f device.crt;
		
		echo 
		echo "###########################################################################"
		echo Done! 
		echo "###########################################################################"
		echo "To use these files on your server, simply copy both $DOMAIN.csr and"
		echo "device.key to your webserver, and use like so (if Apache, for example)"
		echo 
		echo "    SSLCertificateFile    /path_to_your_files/$DOMAIN.crt"
		echo "    SSLCertificateKeyFile /path_to_your_files/device.key"


II.  cp device.key /etc/ssl/private/ssl-cert-snakeoil.key
     cp mysite.com.csr /etc/ssl/certs/ssl-cert-snakeoil.pem

III. a2enmod ssl;
     a2ensite default-ssl.conf; (standard on debian-based distributions) 
     add certs to the SSLCertificateFile and SSLCertificateKeyFile directives in default-ssl.conf
                SSLCertificateFile      /etc/ssl/certs/ssl-cert-snakeoil.pem
                SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key        
     a2dissite 000-default.conf;
     service apache2 restart

In the Chromium broswer: chrome://settings/certificates
  Choose IMPORT in AUTHORITIES
  Upload the public certificate you created, e.g. rootCA.key
  check "Trust this certificate for identifying websites"
    
- LETSENCRYPT
 A preferable alternative would be to use letsencrypt.  If you are using a reverse proxy, usually nginx-proxy,
 make certain that HTTP_X_FORWARDED_FOR is used for identifying the originating IP address, 
 because YBDB shops keep track of their unique ip.
   
TERMINAL AUTOMATION AND SECURITY

Firefox (IceWeasel); note that Chrome below, provides the most recent instructions:
1. Download KeePass v2 zip - http://keepass.info/download.html
2. Unzip in ~/KeePass
3. sudo chown root:root ~/KeePass; sudo chmod 0755 ~/KeePass;
4. cd ~/KeePass; mkdir plugins
5. run .. mono KeePass.exe, create database and a key file in ~/KeePass
6. mv KeePass.config.xml KeePass.config.enforced.xml
7. sudo chown root:root KeePass.config.enforced.xml (and database/key file)
8. sudo chmod 0400 KeePass.config.enforced.xml
9. See Chrome for KeePass.config.enforced.xml policy changes.
10. In Debian/Ubuntu:  apt-get install mono-runtime mono-devel
11. Install KeeFox extension from https://addons.mozilla.org/en-us/firefox/addon/keefox/
12. KeeFox will tell you where to copy KeePassRPC.plgx from into the plugins directory
   Usually somewhere under  ~/.mozilla/firefox/*default/extensions/keefox*
13. When setting up password database for KeePass use only a key file.
14. Add the url along with username and password in the database.
15. Once the login is working properly for the htpasswd setup for apache, 
   the whole process can be completely automated in KeeFox options.
16. In Firefox (IceWeasel) Preferences -> General use "When IceWeasel starts: Show my windows and tabs from the last time"
17. Afterwards, you can sudo chown -R root:root ~/KeePass/*
                        sudo chmod 0400 ~/KeePass/*
	 You may need to make adjustments for plugins.
	 Then run with sudo, see "Chrome (visudo)" to learn how to do this.

Chrome:
1. Install keepass2: sudo apt-get install keepass2

2. Optional: Install libsecret-tools:  sudo apt-get install libsecret-tools
   secret-tool store --label="PositiveSpin" keepass pos (remember password) 
   (Depending on your distribution) Open Menu -> Control Menu -> Security -> Password and Keys
   Right-click on the "login" keyring
   Select "Change password"
   Enter your old password and leave the new password blank
   Press ok
	You may want to remove Password and Keys from the menu,   
   E.g. see https://wiki.lxde.org/en/Main_Menu if using lxde: 
     - sudo mv seahorse.desktop /root; lxpanelctl restart

3. run keepass2;
   create new password database in ~/keepass 
   assign password created with secret-tool to Master password
   create key file in ~/keepass, or even better, in a secret place
   In the password datatase, add the url for YBDB, username and password (created with htpasswd) 
   close keepass2
   sudo chown -R root:root ~/keepass
   sudo chmod -R 0400 ~/keepass (change to 0600 if you want to change password, then back to 0400 when done)

4. SECURITY - The easiest ways to learn about the name of policies which can be disabled are simply 
   to unclick them in Tools -> Options -> Policy, and then look at the additions to <Security></Security> in 
   /usr/lib/keepass2/KeePass.config.xml after exiting the program; security changes don't apply
   until restarting the program. Caveat, make sure that the xml is properly formed.
   These policies can be added between <Policy> in KeePass.config.enforced.xml.  Independently of 
   using KeePass.config.enforced.xml, the key database could be looked at, however, 
   the owner (root), 0400 permissions, and KeePass.config.enforced.xml prevent the database 
   from being copied anywhere, and the key file would be required as well to gain access. 
   
   Secret tools only provides a low-level layer of security with a master password passed by stdin, 
   and is optional (and may be a liability on a public computer). Keepass has auditing capability 
   via triggers, see https://keepass.info/help/kb/trigger_examples.html#audit, if your want to monitor events. 
   It should be noted that keepassxc does not provide the rich set of policies that keepass does, 
   which rules out this newer program.

   cd /usr/lib/keepass2; \ 
   sudo touch KeePass.config.enforced.xml
   
   edit file and add between <Configuration></Configuration>
   
		<?xml version="1.0" encoding="utf-8"?>
		<Configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
		        <Meta>
		                <PreferUserConfiguration>false</PreferUserConfiguration>
		        </Meta>
		        <Security>
		                <Policy>
		                        <UnhidePasswords>false</UnhidePasswords>
		                        <NewFile>false</NewFile>
		                        <SaveFile>false</SaveFile>
		                        <Export>false</Export>
		                        <Import>false</Import>
		                        <Copy>false</Copy>
		                        <Print>false</Print>
		                        <ChangeMasterKey>false</ChangeMasterKey>
		                        <Delete>false</Delete>
		                </Policy>
		               <WorkspaceLocking>
		                        <AlwaysExitInsteadOfLocking>true</AlwaysExitInsteadOfLocking>
		               </WorkspaceLocking>
		        </Security>
		
		</Configuration>

   sudo chmod 0400 KeePass.config.enforced.xml
	
   [doc: https://keepass.info/help/base/configuration.htm]

5. Install keepasshttp from https://github.com/pfn/keepasshttp/ by putting KeePassHttp.plgx in /usr/lib/keepass2;
   sudo chmod 0644 /usr/lib/keepass2/KeePassHttp.plgx
   sudo apt-get install libmono-system-xml-linq4.0-cil libmono-system-data-datasetextensions4.0-cil \
                        libmono-system-runtime-serialization4.0-cil mono-mcs

6. Install chrome extension chromeIPass
   You may have to uncheck: 
        Activate password generator.
        Automatically fill-in single credentials entry.
        Activate autocomplete for username fields

7. Follow the directions chromeIPass gives you, creating an identifier
   https://github.com/pfn/passifox/blob/master/documentation/chromeIPass.md goes into more detail 	
 	
8. sudo su; visudo
   after:   %sudo   ALL=(ALL:ALL) ALL
   add:     pos     ALL=(ALL) NOPASSWD: /usr/bin/keepass2 (note pos is an example user account being used for X11)

9. In Chrome Settings "On Startup Continue where you left off" or 
   "Open a specific page or set of pages" and add the YBDB POS url as one of those specific pages
   
10. Add to desktop startup (see below). Test changes by logging out, and logging back into the WM.
   
DESKTOP STARTUP

1.	LXDE - put a file with this format in ~/.config/autostart with name of *desktop, e.g. keepass.desktop:

[Desktop Entry]
Type=Application
Exec=bash -c "secret-tool lookup keepass pos | sudo keepass2 /home/pos/keepass/PositiveSpin.kdbx -pw-stdin -keyfile:/home/pos/keepass/PositiveSpin.key"

Where keepass2 is a file in /usr/bin (0755 perms)

		#!/bin/sh
		# e.g. in this case KeePass.exe was intalled in users home, rather than /usr/lib/keepass2
		exec /usr/bin/cli /home/pos/KeePass/KeePass.exe "$@"

2.  Gnome based Window manager, e.g. Mate - open gnome-session-properties from commandline, 
	 and add startup application.

SPECIAL NOTES
 
 With the combination of keepass2 and httpasswd, it is possible to fine tune access.  For instance, there could be a 
 sign-in computer allowing access only to shop_log.php, shop_welcome.php, contact_add_edit_select.php, and
 contact_add_edit.php, and another computer for volunteer staff allowing access to almost everything, 
 including transaction_log.php, perhaps with the exclusion of certain reports that should only be available 
 to the volunteer coordinator.
 
 https://wiki.apache.org/httpd/BypassAuthenticationOrAuthorizationRequirements provides good details how this is done:
 
 E.g., we want paid_members.php to be accessible via a completely different password under Apache for our paid members team:
 
                <FilesMatch "\.(php|paid_members\.php)$">
                                SSLOptions +StdEnvVars
                </FilesMatch>
                <Directory /var/www/html/js>
                        Order allow,deny
                        Allow from all
                        Satisfy any
                </Directory>
                <Directory /var/www/html/css>
                        Order allow,deny
                        Allow from all
                        Satisfy any
                </Directory>
                <Directory /var/www/html>
                        Authtype        Basic
                        Authname        "Amazing Community Bike Shop Login"
                        Require         user someuser
                        AuthUserFile    /var/htpasswd
                </Directory>
                <Files "paid_members.php">
                        Authtype        Basic
                        Authname        "Paid Members Login"
                        Require         user paid_members_team
                        AuthUserFile    /var/htpasswd
                </Files>
                
How to get that working with keepass2 should be obvious.

SUSPENDING COMPUTER

Example commands that bring up the gui setting tool:
1. xfce4-power-manager-settings (eg., used by wattos for LXDE)
2. mate-power-manager-settings or mate-power-preferences

BIOS / UEFI (recommended)

Turn off booting of external devices; disable unnecessary external ports; password protect BIOS setup.
Remember the password. There are some ways to reset passwords, if forgotten, but depending on the hardware,
it is not always straight-forward, e.g., resetting the CMOS. 

GRUB2 PASSWORD PROTECT (mandatory)

In order to prevent individuals from casually booting into single mode or a shell,
password protecting GRUB with an encrypted password is mandatory.

https://help.ubuntu.com/community/Grub2/Passwords gives good instructions

1. In /etc/grub.d/10_linux change 

     CLASS="--class gnu-linux --class gnu --class os"
     
     to
     
     CLASS="--class gnu-linux --class gnu --class os --unrestricted"
 
2. Create an encrypted password with grub-mkpasswd-pbkdf2, producing something like

     grub.pbkdf2.sha512.10000.80E702585F80C8D70D4BC75
     
3. In /etc/grub.d/40_custom add:
 
     set superusers="MyUserName"
     password_pbkdf2 MyUserName grub.pbkdf2.sha512.10000.80E702585F80C8D70D4BC75
     # if you are using GRUB 2 1.99 the next line needs to be uncommented
     # export superusers

4. sudo chmod 0700 40_custom

5. update-grub2     

SSD or HD ENCRYPTION (optional)

If a sign-in computers unencrypted drive goes missing (or is stolen), it should (in most cases) 
be pretty obvious, and you would want to change YBDB's htpasswd and root password for the computer. However, if you 
want to "help" prevent a detached drive from being accessed, utilitizing an encrypted partition or file container,
for the keepass2 system discussed above, would be one way to go, although, even that can be accessed with a few steps,
and some forensics (https://dfir.science/2014/08/how-to-brute-forcing-password-cracking.html). While most modern 
distributions provide an option to encrypt the whole installation, some good reasons for not wanting to do this 
include a performance hit, and a more complex recovery. When deciding to go the encryption route, you need to weigh 
in the advantages and disadvantages for encrypting while factoring into the equation the nature of the environment 
the computer will be located within.

SUMMARY

There are other things that can be done within the terminal to prevent tampering, e.g., kiosk or read-only environment, 
an expect or curl script, etc. rather than KeePass, but what is above protects the password from hacking, eavesdropping, 
and from regular users in the shop, basically, only the sysadmin and bookkeeper should have remote access via the password. 
So while YBDB is on the internet, it will only be available to the terminal(s) you allow it to be on, and
the Point of Sale will be at the proper location which is usually the front of the Community Bike Shop where people
walk-in/walk-out.

Word of wisdom:  It is always good practice to occasionally change the password. 
