-
Notifications
You must be signed in to change notification settings - Fork 0
/
inbox.php
393 lines (364 loc) · 15.8 KB
/
inbox.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// form a connection to the SQL database
include_once 'db_config.php';
session_start();
function redirect($url) {
header('Location: '.$url);
die();
}
//define a function which logs out the user
function logout(){
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
redirect("login.php");
}
//define a function which generates public and private keys
function generate_keys($encryption_method = "ring_lwe"){
$command = escapeshellcmd('/home/jackson/open_encrypt/openencryptvenv/bin/python3 keygen_' . $encryption_method . '.py');
$json_string = shell_exec($command);
try{
$json_object = json_decode($json_string, true, 512, JSON_THROW_ON_ERROR);
}
catch(Exception $e){
print $e;
}
return $json_object;
}
//encrypt a message using the given public key
function encrypt_message($public_key,$plaintext,$encryption_method="ring_lwe"){
$command = escapeshellcmd('/home/jackson/open_encrypt/openencryptvenv/bin/python3 encrypt_' . $encryption_method . '.py' . ' ' . $public_key . ' ' . $plaintext);
$encrypted_string = shell_exec($command);
return $encrypted_string;
}
//decrypt a message using the secret key
function decrypt_message($secret_key,$ciphertext,$encryption_method="ring_lwe"){
$command = escapeshellcmd('/home/jackson/open_encrypt/openencryptvenv/bin/python3 decrypt_' . $encryption_method . '.py' . ' ' . $secret_key . ' ' . $ciphertext);
$decrypted_string = shell_exec($command);
return $decrypted_string;
}
//retrieve the public key from the database for the given username
function fetch_public_key($username,$conn){
if(username_exists($username,"public_keys",$conn)){
$sql_select = "SELECT public_key FROM `public_keys` WHERE `username` = '$username'";
try{
if ($result = mysqli_query($conn, $sql_select)) {
$row = $result->fetch_assoc();
return $row['public_key'];
}
}
catch(Exception $e) {
echo "Error: " . $sql_select . "<br>" . mysqli_error($conn);
}
}
}
//retrieve the encryption method from the database for the given username
function fetch_encryption_method($username,$conn){
if(username_exists($username,"public_keys",$conn)){
$sql_select = "SELECT method FROM `public_keys` WHERE `username` = '$username'";
try{
if ($result = mysqli_query($conn, $sql_select)) {
$row = $result->fetch_assoc();
return $row['method'];
}
}
catch(Exception $e) {
echo "Error: " . $sql_select . "<br>" . mysqli_error($conn);
}
}
}
//function to check whether a username exists in login_info table in database users
function username_exists($username,$table,$conn){
$sql_check = "SELECT COUNT(*) FROM $table WHERE username = '$username'";
try{
if ($result = mysqli_query($conn, $sql_check)) {
$row = $result->fetch_assoc();
if($row['COUNT(*)'] > 0){
return true;
}
else{
return false;
}
}
}
catch(Exception $e) {
echo "Error: " . $sql_check . "<br>" . mysqli_error($conn);
}
}
// validate user input from forms
function valid_input($user_input,$max_len){
if (empty($user_input)) {
return false;
}
// To check that username only contains alphabets, numbers, and underscores
if (!preg_match("/^[a-zA-Z0-9_]*$/", $user_input)) {
return false;
}
if (strlen($user_input) > $max_len) {
return false;
}
return true;
}
// validate user input from forms
function valid_secret_key($secret_key,$encryption_method="ring_lwe"){
//check if secret key is empty string
if (empty($secret_key)) {
return false;
}
//for ring-LWE, check secret key only contains characters 0 or 1, i.e. binary string
if($encryption_method == "ring_lwe"){
if (!preg_match("/^[0-1]*$/", $secret_key)) {
return false;
}
if (strlen($secret_key) > 16) {
return false;
}
}
//for module-LWE, check secret key only contains characters in {'-',',','0','1'}, i.e. ternary array
if($encryption_method == "module_lwe"){
if(!preg_match("/^[-01,]*$/", $secret_key)) {
return false;
}
if (strlen($secret_key) > 20) {
return false;
}
}
return true;
}
?>
<html>
<head>
<title>Open Encrypt</title>
</head>
<body>
<h1>Under construction.</h1>
</body>
<a href="index.html">Home</a>
<a href="inbox.php">Messages</a>
<form method="post">
<input type="submit" name="logout" class="button" value="Logout" />
</form>
<?php
if (isset($_SESSION['user'])) {
echo "Welcome to your inbox: " . $_SESSION['user'];
}
else{
logout();
}
?>
<form action="inbox.php" method="POST">
To: <input type="text" id="to" name="to">
Message: <input type="text" id="message" name="message">
<input type="submit" value="Send">
</form>
<form method="post">
<input type="submit" name="key_gen" class="button" value="Generate Keys" />
<input type="radio" id="ring_lwe" name="encryption_method" value="ring_lwe">
<label for="ring_lwe">ring-LWE</label>
<input type="radio" id="module_lwe" name="encryption_method" value="module_lwe">
<label for="module_lwe">module-LWE</label>
</form>
<form method="post">
<input type="submit" name="save_keys" class="button" value="Save Public Key" />
</form>
<form method="post">
<input type="submit" name="view_keys" class="button" value="View Public Key" />
</form>
<?php
//if the "key generation" button is pressed and there is a valid user session, generate public/private key pair
if (isset($_POST['key_gen']) && isset($_SESSION['user']) && isset($_POST['encryption_method'])){
$encryption_method = $_POST['encryption_method'];
$json_keys = generate_keys($encryption_method);
if($encryption_method == "ring_lwe"){
$secret_key = implode('', $json_keys["secret"]);
$public_key_b = implode(',', $json_keys["public_b"]);
$public_key_a = implode(',', $json_keys["public_a"]);
$public_key = $public_key_b . "," . $public_key_a;
}
if($encryption_method == "module_lwe"){
$secret_key = implode(',', $json_keys["secret"]);
$public_key_A = implode(',', $json_keys["public_A"]);
$public_key_t = implode(',', $json_keys["public_t"]);
$public_key = $public_key_A . ',' . $public_key_t;
}
echo "Secret key ($encryption_method): This is private and should be written down and stored safely. It is used to decrypt messages you've received.<br><br>";
echo $secret_key;
echo "<br><br>";
echo "Public key ($encryption_method): This is public and is stored on the server. It is used for encrypting messages sent to you.<br><br>";
echo $public_key;
echo "<br><br>";
//set the public key and encryption method as session variables to be used for "save keys"
$_SESSION['public_key'] = $public_key;
$_SESSION['encryption_method'] = $encryption_method;
}
?>
<?php
//save public key
if(isset($_POST['save_keys']) && isset($_SESSION['user']) && isset($_SESSION['public_key']) && isset($_SESSION['encryption_method'])){
$username = $_SESSION['user'];
$public_key = $_SESSION['public_key'];
$encryption_method = $_SESSION['encryption_method'];
// form the sql string to insert the public_key into table public_keys
if(!username_exists($username,"public_keys",$conn)){
$sql_insert = "INSERT INTO `public_keys` (`username`, `public_key`, `method`) VALUES ('$username', '$public_key', '$encryption_method')";
echo "Trying SQL insertion...";
try{
if (mysqli_query($conn, $sql_insert)) {
echo "Success: $encryption_method public key inserted into SQL database for $username.<br>";
unset($_SESSION['public_key']);
unset($_SESSION['encryption_method']);
}
}
catch(Exception $e) {
echo "Error: " . $sql_insert . "<br>" . mysqli_error($conn);
}
}
else{
echo "Public key already exists for $username. Updating public key...<br>";
$sql_update = "UPDATE public_keys SET public_key = '$public_key', method = '$encryption_method' WHERE username = '$username'";
try{
if (mysqli_query($conn, $sql_update)) {
echo "Success: $encryption_method public key updated for $username.<br>";
unset($_SESSION['public_key']);
unset($_SESSION['encryption_method']);
}
}
catch(Exception $e) {
echo "Error: " . $sql_insert . "<br>" . mysqli_error($conn);
}
}
}
?>
<?php
//view public key and encryption method
if(isset($_POST['view_keys']) && isset($_SESSION['user'])){
$username = $_SESSION['user'];
echo "public_key: " . fetch_public_key($username,$conn) . "<br>";
echo "encryption_method: " . fetch_encryption_method($username,$conn) . "<br>";
}
?>
<?php
//send message
if (isset($_SESSION['user']) and isset($_POST['to']) and isset($_POST['message'])){
//set the variables with message data and metadata
$from_username = $_SESSION['user'];
$to_username = $_POST['to'];
$message = $_POST['message'];
//get the encryption method used by $to_username
$encryption_method = fetch_encryption_method($to_username,$conn);
$valid_recipient = valid_input($to_username,14);
if (!$valid_recipient){
echo "Error: Invalid recipient.<br>";
}
$valid_message = valid_input($message,240);
if (!$valid_message){
echo "Error: Invalid message.<br>";
}
if(username_exists($to_username,"login_info",$conn) and $valid_recipient and $valid_message){
$public_key = fetch_public_key($to_username,$conn);
$encrypted_message = encrypt_message($public_key,$message,$encryption_method);
// form the sql string to insert the message into the tables messages
$sql_insert = "INSERT INTO `messages` (`from`, `to`, `message`,`method`) VALUES ('$from_username', '$to_username','$encrypted_message','$encryption_method')";
echo "Trying SQL insertion...";
try{
if (mysqli_query($conn, $sql_insert)) {
echo "Success: message sent from $from_username to $to_username using $encryption_method.<br>";
}
}
catch(Exception $e) {
echo "Error: " . $sql_insert . "<br>" . mysqli_error($conn);
}
}
else{
echo "Error: username does not exist or invalid recipient or invalid message.<br>";
}
}
?>
<?php
echo "-----------------------------------------------------------<br><br>";
?>
<form method="post">
<label for="secret_key">Secret Key:</label>
<input type="text" id="secret_key" name="secret_key">
<input type="submit" name="decrypt_messages" class="button" value="Decrypt Messages" />
<input type="radio" id="ring_lwe" name="encryption_method" value="ring_lwe">
<label for="ring_lwe">ring-LWE</label>
<input type="radio" id="module_lwe" name="encryption_method" value="module_lwe">
<label for="module_lwe">module-LWE</label>
</form>
<form method="post">
<input type="submit" name="view_messages" class="button" value="View Messages" />
</form>
<?php
//display all the encrypted messages sent to the current user
if(isset($_SESSION['user']) && isset($_POST['view_messages'])){
$username = $_SESSION['user'];
$sql_get_messages = "SELECT * FROM messages WHERE `to` = '$username'";
echo "Trying to retrieve messages...<br><br>";
try{
if ($result = mysqli_query($conn, $sql_get_messages)) {
echo "retrieved messages successfully.<br><br>";
while($row = $result->fetch_assoc()){
echo $row['from'] . "-->" . $row['to'] . ' (' . $row['method'] . "): ";
echo $row['message'];
echo "<br>";
}
}
}
catch(Exception $e) {
echo "Error: " . $sql_get_messages . "<br>" . mysqli_error($conn);
}
}
?>
<?php
//decrypt messages sent to the current user using the provided secret key
if(isset($_SESSION['user']) && isset($_POST['decrypt_messages']) && isset($_POST['secret_key']) && isset($_POST['encryption_method'])){
$username = $_SESSION['user'];
$secret_key = $_POST['secret_key'];
$secret_key_method = $_POST['encryption_method'];
if (!valid_secret_key($secret_key,$secret_key_method)){
echo "Error: Invalid secret key.";
}
else{
$sql_get_messages = "SELECT * FROM messages WHERE `to` = '$username'";
try{
if ($result = mysqli_query($conn, $sql_get_messages)) {
echo "Retrieved messages successfully...";
echo "Trying to decrypt messages...<br><br>";
while($row = $result->fetch_assoc()){
echo $row['from'] . "-->" . $row['to'] . ": ";
if($secret_key_method == $row['method']){
$decrypted_message = decrypt_message($secret_key,$row['message'],$row['method']);
echo $decrypted_message;
}
else{
echo "[different encryption method]";
}
echo "<br>";
}
}
}
catch(Exception $e) {
echo "Error: " . $sql_get_messages . "<br>" . mysqli_error($conn);
}
}
}
?>
<?php
if(array_key_exists('logout', $_POST)) {
logout();
}
?>
</html>