class Session

Provides functions for managing user sessions in a security-conscious manner.

Traits

Validate that email address conforms to specification.
Validate that a URL meets the specification.
Provides methods for validating UTF-8 character encoding and string composition.

Methods

bool
isEmail(string $email)

Check if an email address is valid.

bool
isUrl(string $url)

Validate URL.

from UrlCheck
string
encodeEscapeUrl(string $url)

URL-encode and escape a query string for use in a URL.

bool
isAlnum(string $alnum)

Check that a string is comprised solely of alphanumeric characters.

bool
isAlnumUnderscore(string $alnumUnderscore)

Check that a string is comprised solely of alphanumeric characters and underscores.

bool
isAlpha(string $alpha)

Check that a string is comprised solely of alphabetical characters.

bool
isUtf8(string $text)

Check if the character encoding of text is UTF-8.

string
trimString(mixed $text)

Cast to string, check UTF-8 encoding and strip trailing whitespace and control characters.

__construct(Database $db, Preference $preference)

Constructor.

destroy()

Unset session variables and destroy the session.

string
getLoginLink()

Returns a login or logout link for insertion in the template.

bool
isAdmin()

Shorthand admin privileges check.

bool
isClean()

Checks if client IP address or user agent has changed.

bool
isExpired()

Checks if a session has expired and sets last seen activity flag.

login(string $email, string $password)

Authenticate the user and establish a session.

string
hashPassword(string $password)

Hashes and salts a password to harden it against dictionary attacks.

logout(string $urlRedirect = '')

Destroys the current session on logout

regenerate()

Regenerates the session ID.

reset()

Reset session data after a session hijacking check fails. This will force logout.

start()

Initialises a session and sets session cookie parameters to security-conscious values.

setToken()

Sets a token for use in cross-site request forgery checks on form submissions.

twoFactorLogin(string $dirtyPassword, string $dirtyOtp, Auth_yubico $yubikey)

Authenticate the user with two factors and establish a session.

Details

in EmailCheck at line 39
bool isEmail(string $email)

Check if an email address is valid.

Note that valid email addresses can contain database-unsafe characters such as single quotes.

Parameters

string $email Input to be tested.

Return Value

bool True if a valid email address, otherwise false.

in UrlCheck at line 40
bool isUrl(string $url)

Validate URL.

Only accepts http:// and https:// protocol and ASCII characters. Other protocols and internationalised domain names will fail validation due to limitation of filter.

Parameters

string $url Input to be tested.

Return Value

bool True if valid URL otherwise false.

in ValidateString at line 41
string encodeEscapeUrl(string $url)

URL-encode and escape a query string for use in a URL.

Trims, checks for UTF-8 compliance, rawurlencodes and then escapes with htmlspecialchars(). If you wish to use the data on a landing page you must decode it with htmlspecialchars_decode() followed by rawurldecode() in that order. But really, if you are using any characters that need to be encoded in the first place you should probably just stop.

Parameters

string $url Unescaped input URL.

Return Value

string Encoded and escaped URL.

in ValidateString at line 59
bool isAlnum(string $alnum)

Check that a string is comprised solely of alphanumeric characters.

Accented regional characters are rejected. This method is designed to be used to check database identifiers or object property names.

Parameters

string $alnum Input to be tested.

Return Value

bool True if valid alphanumerical string, false otherwise.

in ValidateString at line 77
bool isAlnumUnderscore(string $alnumUnderscore)

Check that a string is comprised solely of alphanumeric characters and underscores.

Accented regional characters are rejected. This method is designed to be used to check database identifiers or object property names.

Parameters

string $alnumUnderscore Input to be tested.

Return Value

bool True if valid alphanumerical or underscore string, false otherwise.

in ValidateString at line 95
bool isAlpha(string $alpha)

Check that a string is comprised solely of alphabetical characters.

Tolerates vanilla ASCII only. Accented regional characters are rejected. This method is designed to be used to check database identifiers or object property names.

Parameters

string $alpha Input to be tested.

Return Value

bool True if valid alphabetical string, false otherwise.

in ValidateString at line 113
bool isUtf8(string $text)

Check if the character encoding of text is UTF-8.

All strings received from external sources must be passed through this function, particularly prior to storage in the database.

Parameters

string $text Input string to check.

Return Value

bool True if string is UTF-8 encoded otherwise false.

in ValidateString at line 131
string trimString(mixed $text)

Cast to string, check UTF-8 encoding and strip trailing whitespace and control characters.

Removes trailing whitespace and control characters (ASCII <= 32 / UTF-8 points 0-32 inclusive), checks for UTF-8 character set and casts input to a string. Note that the data returned by this function still requires escaping at the point of use; it is not database or XSS safe.

As the input is cast to a string do NOT apply this function to non-string types (int, float, bool, object, resource, null, array, etc).

Parameters

mixed $text Input to be trimmed.

Return Value

string Trimmed and UTF-8 validated string.

at line 50
__construct(Database $db, Preference $preference)

Constructor.

Parameters

Database $db Database instance.
Preference $preference Instance of Tuskfish preference class.

at line 62
destroy()

Unset session variables and destroy the session.

Returns a login or logout link for insertion in the template.

Return Value

string HTML login or logout link.

at line 92
bool isAdmin()

Shorthand admin privileges check.

For added security this could retrieve an encrypted token, preferably the SSL session id, although thats availability seems to depend on server configuration.

Return Value

bool True if admin false if not.

at line 109
bool isClean()

Checks if client IP address or user agent has changed.

These tests can indicate session hijacking but are by no means definitive; however they do indicate elevated risk and the session should be regenerated as a counter measure.

Return Value

bool True if IP/user agent are unchanged, false otherwise.

at line 137
bool isExpired()

Checks if a session has expired and sets last seen activity flag.

Return Value

bool True if session has expired, false if not.

at line 171
login(string $email, string $password)

Authenticate the user and establish a session.

The number of failed login attempts is tracked. Subsequent login attempts will sleep for an equivalent number of seconds before processing, in order to frustrate brute force attacks. A successful login will reset the counter to zero. Note that the password field is unrestricted content.

Parameters

string $email Input email.
string $password Input password.

at line 277
string hashPassword(string $password)

Hashes and salts a password to harden it against dictionary attacks.

Uses the default password hashing algorithm, which wa bcrypt as of PHP 7.2, with a cost of 11. If logging in is too slow, you could consider reducing this to 10 (the default value). Lowering it further will weaken the security of the hash.

Parameters

string $password Input password.

Return Value

string Password hash, incorporating algorithm and difficulty information.

at line 290
logout(string $urlRedirect = '')

Destroys the current session on logout

Parameters

string $urlRedirect The URL to redirect the user to on logging out.

at line 339
regenerate()

Regenerates the session ID.

Called whenever there is a privilege escalation (login) or at random intervals to reduce risk of session hijacking. Note that the cross-site request forgery validation token remains the same, unless the session is destroyed. This is to prevent the random session ID regeneration events creating false positive CSRF checks.

Note that it allows the new and old sessions to co-exist for a short period, this is to avoid headaches with flaky network connections and asynchronous (AJAX) requests, as explained in the PHP Manual warning: http://php.net/manual/en/function.session-regenerate-id.php

at line 370
reset()

Reset session data after a session hijacking check fails. This will force logout.

at line 389
start()

Initialises a session and sets session cookie parameters to security-conscious values.

at line 444
setToken()

Sets a token for use in cross-site request forgery checks on form submissions.

A random token is generated and stored in the current session (if not already set). The value of this token is included as a hidden field in forms when they are loaded by the user. This allows forms to be validated via validateFormToken().

at line 462
twoFactorLogin(string $dirtyPassword, string $dirtyOtp, Auth_yubico $yubikey)

Authenticate the user with two factors and establish a session.

Requires a Yubikey hardware token as the second factor. Note that the authenticator type is not declared, as the desired response is to logout and redirect, rather than to throw an error.

Parameters

string $dirtyPassword Input password.
string $dirtyOtp Input Yubikey one-time password.
Auth_yubico $yubikey Instance of the Yubico authenticator class.