forked from zaporylie/drupal-sshkey
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsshkey.module
More file actions
541 lines (475 loc) · 15.9 KB
/
sshkey.module
File metadata and controls
541 lines (475 loc) · 15.9 KB
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
<?php
/**
* @file
* Allows SSH keys to be associated with entities.
*/
/**
* Return value for hook_sshkey_access() to allow access to an SSH key.
*/
define('SSHKEY_ACCESS_ALLOW', 'allow');
/**
* Return value for hook_sshkey_access() to deny access to a SSH key.
*/
define('SSHKEY_ACCESS_DENY', 'deny');
/**
* Return value for hook_sshkey_access() to not affect SSH key access.
*/
define('SSHKEY_ACCESS_IGNORE', NULL);
/**
* Exception thrown if a public key does not parse correctly.
*/
class SSHKeyParseException extends Exception {
}
/**
* Implements hook_help().
*/
function sshkey_help($path, $arg) {
switch ($path) {
case 'user/%/ssh-keys':
case 'ssh-keys/%/%':
case 'ssh-keys/%/%/add':
if ($help_text = variable_get('sshkey_help', t('Need help with public keys? View the excellent GitHub.com SSH public key help at <a href="http://github.com/guides/providing-your-ssh-key" target="_blank">http://github.com/guides/providing-your-ssh-key</a>.'))) {
return '<p>' . filter_xss_admin($help_text) . '</p>';
}
}
}
/**
* Implements hook_permission().
*/
function sshkey_permission() {
$perm = array(
'view any SSH public keys' => array(
'title' => t('View any SSH public keys'),
),
'view own SSH public keys' => array(
'title' => t('View own SSH public keys'),
),
'edit any SSH public keys' => array(
'title' => t('Edit any SSH public keys'),
'restrict access' => TRUE,
),
'edit own SSH public keys' => array(
'title' => t('Edit own SSH public keys'),
),
'manage any SSH public keys' => array(
'title' => t('Create and delete any SSH public keys'),
'restrict access' => TRUE,
),
'manage own SSH public keys' => array(
'title' => t('Create and delete own SSH public keys'),
),
'administer SSH public keys' => array(
'title' => t('Administer SSH public keys'),
'restrict access' => TRUE,
),
);
return $perm;
}
/**
* Implements hook_menu().
*/
function sshkey_menu() {
$items['user/%/ssh-keys'] = array(
'title' => 'SSH keys',
'page callback' => 'sshkey_list_page',
'page arguments' => array('user', 1),
'access callback' => 'sshkey_access',
'access arguments' => array('view', 'user', 1),
'file' => 'sshkey.pages.inc',
'type' => MENU_LOCAL_TASK,
'weight' => 10,
);
// The first two arguments for the following CRUD pages are entity type,
// followed by entity ID.
$items['ssh-keys/%/%/add'] = array(
'title' => 'Add a SSH key',
'page callback' => 'drupal_get_form',
'page arguments' => array('sshkey_edit_form', 1, 2),
'access callback' => 'sshkey_access',
'access arguments' => array('create', 1, 2),
'file' => 'sshkey.pages.inc',
'modal' => TRUE,
);
$items['ssh-keys/%/%/%sshkey/view'] = array(
'title' => 'View SSH key',
'page callback' => 'sshkey_view_key',
'page arguments' => array(1, 2, 3),
'access callback' => 'sshkey_access',
'access arguments' => array('view', 1, 2, 3),
'file' => 'sshkey.pages.inc',
);
$items['ssh-keys/%/%/%sshkey/edit'] = array(
'title' => 'Edit SSH key',
'page callback' => 'drupal_get_form',
'page arguments' => array('sshkey_edit_form', 1, 2, 3),
'access callback' => 'sshkey_access',
'access arguments' => array('edit', 1, 2, 3),
'file' => 'sshkey.pages.inc',
'modal' => TRUE,
);
$items['ssh-keys/%/%/%sshkey/delete'] = array(
'title' => 'Delete SSH key',
'page callback' => 'drupal_get_form',
'page arguments' => array('sshkey_delete_form', 3),
'access callback' => 'sshkey_access',
'access arguments' => array('delete', 1, 2, 3),
'file' => 'sshkey.pages.inc',
'modal' => TRUE,
);
$items['admin/config/system/ssh-keys'] = array(
'title' => 'SSH public key settings',
'description' => 'Configure the SSH public key settings.',
'page callback' => 'drupal_get_form',
'page arguments' => array('sshkey_settings_form'),
'access arguments' => array('administer SSH public keys'),
'file' => 'sshkey.admin.inc',
);
return $items;
}
/**
* Implements hook_theme().
*/
function sshkey_theme($existing, $type, $theme, $path) {
$info['sshkey_fingerprint'] = array(
'variables' => array('key' => NULL),
);
return $info;
}
/**
* Access callback for SSH public key operations.
*/
function sshkey_access($op, $entity_type = NULL, $entity_id = NULL, $key = NULL, $account = NULL) {
$rights = &drupal_static(__FUNCTION__, array());
if (!in_array($op, array('view', 'create', 'edit', 'delete'), TRUE)) {
// If $op was not one of the supported ones, we return access denied.
return FALSE;
}
// Default user_access() checks to use the current user.
if (!isset($account)) {
$account = $GLOBALS['user'];
}
$cid = is_object($key) ? $key->key_id : 0;
// Make sure the entity type and IDs match the existing key's entity data.
if (is_object($key)) {
if (isset($entity_type) && $key->entity_type != $entity_type) {
return FALSE;
}
elseif (isset($entity_id) && $key->entity_id != $entity_id) {
return FALSE;
}
}
// Make sure that an actual entity object exists to attach to.
if (!entity_load($entity_type, array($entity_id))) {
return FALSE;
}
// If we've already checked access for this key, user and op, return from
// cache.
if (isset($rights[$account->uid][$cid][$op])) {
return $rights[$account->uid][$cid][$op];
}
// Admins can do everything.
if (user_access('administer SSH public keys', $account)) {
$rights[$account->uid][$cid][$op] = TRUE;
return TRUE;
}
// We grant access to the key if both of the following conditions are met:
// - No modules say to deny access.
// - At least one module says to grant access.
$access = module_invoke_all('sshkey_access', $op, $entity_type, $entity_id, $key, $account);
if (in_array(SSHKEY_ACCESS_DENY, $access, TRUE)) {
$rights[$account->uid][$cid][$op] = FALSE;
return FALSE;
}
elseif (in_array(SSHKEY_ACCESS_ALLOW, $access, TRUE)) {
$rights[$account->uid][$cid][$op] = TRUE;
return TRUE;
}
return FALSE;
}
/**
* Implements hook_sshkey_access().
*/
function sshkey_sshkey_access($op, $entity_type, $entity_id, $key, $account) {
if ($op == 'view') {
if (user_access('view any SSH public keys')) {
return SSHKEY_ACCESS_ALLOW;
}
else {
$entity = entity_load($entity_type, array($entity_id));
$entity = reset($entity);
if (isset($entity->uid) && $entity->uid == $account->uid && user_access('view own SSH public keys')) {
return SSHKEY_ACCESS_ALLOW;
}
}
}
elseif ($op == 'edit') {
if (user_access('edit any SSH public keys')) {
return SSHKEY_ACCESS_ALLOW;
}
else {
$entity = entity_load($entity_type, array($entity_id));
$entity = reset($entity);
if (isset($entity->uid) && $entity->uid == $account->uid && user_access('edit own SSH public keys')) {
return SSHKEY_ACCESS_ALLOW;
}
}
}
else {
if (user_access('manage any SSH public keys')) {
return SSHKEY_ACCESS_ALLOW;
}
else {
$entity = entity_load($entity_type, array($entity_id));
$entity = reset($entity);
if (isset($entity->uid) && $entity->uid == $account->uid && user_access('manage own SSH public keys')) {
return SSHKEY_ACCESS_ALLOW;
}
}
}
return SSHKEY_ACCESS_IGNORE;
}
/**
* Load an SSH public key and optionally by entity type and ID.
*/
function sshkey_load($key_id, $reset = FALSE) {
$keys = entity_load('sshkey', array($key_id), array(), $reset);
return !empty($keys) ? reset($keys) : FALSE;
}
/**
* Load an SSH public key by fingerprint.
*/
function sshkey_load_by_fingerprint($fingerprint) {
$keys = entity_load('sshkey', FALSE, array('fingerprint' => $fingerprint));
return !empty($keys) ? reset($keys) : FALSE;
}
/**
* Load all SSH public keys associated with an entity.
*/
function sshkey_load_all_by_entity($entity_type, $entity_id) {
return entity_load('sshkey', FALSE, array('entity_type' => $entity_type, 'entity_id' => $entity_id));
}
/**
* Load multiple SSH public keys.
*/
function sshkey_load_multiple($key_ids = array(), array $conditions = array(), $reset = FALSE) {
return entity_load('sshkey', $key_ids, $conditions, $reset);
}
/**
* Save a SSH public key.
*/
function sshkey_save($key) {
$transaction = db_transaction();
try {
if (!empty($key->key_id) && !isset($key->original)) {
$key->original = entity_load_unchanged('sshkey', $key->key_id);
}
// Determine if we will be inserting a new node.
if (!isset($key->is_new)) {
$key->is_new = empty($key->key_id);
}
// The changed timestamp is always updated for bookkeeping purposes.
$key->changed = time();
if (!isset($key->entity_type) && !isset($key->entity_id)) {
$key->entity_type = 'user';
$key->entity_id = $GLOBALS['user']->uid;
}
// Re-fingerprint the key.
$parsed = sshkey_parse($key->value);
$key->fingerprint = $parsed['fingerprint'];
$key->value = $parsed['value'];
// Add a default name based on public key comment if available.
if (empty($key->title)) {
if (isset($parsed['comment'])) {
$key->title = truncate_utf8($parsed['comment'], 128, TRUE);
}
else {
$key->title = truncate_utf8($key->value, 26, FALSE);
}
}
// Allow other modules to alter the public key before saving.
module_invoke_all('sshkey_presave', $key);
module_invoke_all('entity_presave', $key, 'sshkey');
// Save the key to the database and invoke the post-save hooks.
if ($key->is_new) {
drupal_write_record('sshkey', $key);
module_invoke_all('sshkey_insert', $key);
module_invoke_all('entity_insert', $key, 'sshkey');
watchdog('sshkey', 'Added new SSH key %key (@fingerprint).', array('%key' => $key->title, '@fingerprint' => $key->fingerprint));
}
else {
drupal_write_record('sshkey', $key, array('key_id'));
module_invoke_all('sshkey_update', $key);
module_invoke_all('entity_update', $key, 'sshkey');
watchdog('sshkey', 'Updated SSH key %key (@fingerprint).', array('%key' => $key->title, '@fingerprint' => $key->fingerprint));
}
// Clear internal properties.
unset($key->is_new);
unset($key->original);
// Clear the static loading cache.
entity_get_controller('sshkey')->resetCache(array($key->key_id));
// Ignore slave server temporarily to give time for the
// saved node to be propagated to the slave.
db_ignore_slave();
}
catch (Exception $e) {
$transaction->rollback();
watchdog_exception('sshkey', $e);
throw $e;
}
}
/**
* Delete an SSH public key.
*/
function sshkey_delete($key_ids) {
return sshkey_delete_multiple(array($key_ids));
}
/**
* Delete multiple SSH public keys.
*/
function sshkey_delete_multiple($key_ids) {
if (empty($key_ids)) {
return;
}
$transaction = db_transaction();
try {
$keys = sshkey_load_multiple($key_ids);
foreach ($keys as $key_id => $key) {
module_invoke_all('sshkey_delete', $key);
module_invoke_all('entity_delete', $key, 'sshkey');
watchdog('sshkey', 'Deleted SSH key %key (@fingerprint).', array('%key' => $key->title, '@fingerprint' => $key->fingerprint));
}
db_delete('sshkey')
->condition('key_id', $key_ids, 'IN')
->execute();
}
catch (Exception $e) {
$transaction->rollback();
watchdog_exception('sshkey', $e);
throw $e;
}
// Clear the entity caches.
entity_get_controller('sshkey')->resetCache();
}
/**
* Delete all SSH public keys associated with an entity.
*/
function sshkey_delete_all_by_entity($entity_type, $entity_id) {
$key_ids = db_query("SELECT key_id FROM {sshkey} WHERE entity_type = :entitytype AND entity_id = :entityid", array(':entitytype' => $entity_type, ':entityid' => $entity_id))->fetchCol();
return !empty($key_ids) ? sshkey_delete_multiple($key_ids) : FALSE;
}
/**
* Validate an SSH public key.
*/
function sshkey_validate($key, $form, &$form_state) {
$key = (object) $key;
try {
$parsed = sshkey_parse($key->value);
$existing_key = sshkey_load_by_fingerprint($parsed['fingerprint']);
if (!empty($existing_key->key_id) && $existing_key->key_id != $key->key_id) {
form_set_error('value', t('The public key with fingerprint %fingerprint is already in use.', array('%fingerprint' => $parsed['fingerprint'])));
}
}
catch (SSHKeyParseException $e) {
form_set_error('value', $e->getMessage());
return;
}
// Allow other modules to validate the SSH public key.
foreach (module_implements('sshkey_validate') as $module) {
$function = $module . '_sshkey_validate';
$function($key, $form, $form_state, $parsed);
}
}
/**
* Parses a SSH public key.
*
* @param string $key_raw
* The string with the raw SSH public key.
*/
function sshkey_parse($key_raw) {
$parsed['value'] = sshkey_clean_whitespace($key_raw);
// The SSH key should be a string in the form:
// "<algorithm type> <base64-encoded key> <comment>".
$key_parts = explode(' ', $parsed['value'], 3);
if (count($key_parts) < 2) {
throw new SSHKeyParseException(t('The key is invalid.'));
}
$parsed['algorithm'] = $key_parts[0];
$algorithms = variable_get('sshkey_algorithms', [
'ssh-rsa',
'ssh-dss',
'ssh-ed25519',
]);
if (!in_array($parsed['algorithm'], $algorithms)) {
// Produces a string like "ssh-rsa, ssh-dss, or ssh-ed25519".
$algorithm_string = implode(', or ', array_merge(
[implode(', ', array_slice($algorithms, 0, -1))],
array_slice($algorithms, -1)
));
throw new SSHKeyParseException(t('The key is invalid. It must begin with @algorithms.', ['@algorithms' => $algorithm_string]));
}
$parsed['key'] = $key_parts[1];
// Decode the key, if it is valid base64.
$key_base64_decoded = base64_decode($parsed['key'], TRUE);
if ($key_base64_decoded === FALSE) {
throw new SSHKeyParseException(t('The key could not be decoded.'));
}
// Check if the data has okay data.
$expected_prefix = pack('N', strlen($parsed['algorithm'])) . $parsed['algorithm'];
if (strpos($key_base64_decoded, $expected_prefix) !== 0) {
throw new SSHKeyParseException(t('The key is invalid. It is not a public key.'));
}
$parsed['fingerprint'] = md5($key_base64_decoded);
if (isset($key_parts[2])) {
$parsed['comment'] = $key_parts[2];
}
return $parsed;
}
/**
* Attempt to clean up extra whitespace in the key, before parsing.
*
* @param string $key_raw
* The raw (provided) key.
*
* @return string
* A key containing correct whitespace.
*/
function sshkey_clean_whitespace($key_raw) {
// Replace all consecutive whitespace characters with a single space.
$key = trim(preg_replace('/\s+/', ' ', $key_raw));
// Ignore keys that contain just 1 space.
if (substr_count($key, ' ') <= 1) {
return $key;
}
// Split the key type (e.g. 'ssh-rsa') from the rest of the key.
list($type, $rest) = explode(' ', $key, 2);
// Go through the space-separated parts of $rest, concatenating them into
// $value, to create the longest possible base64-encoded string. Any
// left-over parts will be considered as the key's "comment".
$value = '';
$comment = '';
$parts = explode(' ', $rest);
foreach ($parts as $index => $part) {
$valid = $value !== '' && base64_decode($value, TRUE) !== FALSE;
$valid_next = $value !== '' && base64_decode($value . $part, TRUE) !== FALSE;
if ($valid && !$valid_next) {
$comment = implode(' ', array_slice($parts, $index));
break;
}
$value .= $part;
}
// If it was not possible to generate any valid base64-encoded string, then
// return the key with all spaces preserved. The key will probably fail
// validation.
if (empty($valid)) {
return $key;
}
return trim($type . ' ' . $value . ' ' . $comment);
}
/**
* Theme callback to output a formatted SSH key fingerprint.
*/
function theme_sshkey_fingerprint($variables) {
$key = $variables['key'];
$chunks = str_split($key->fingerprint, 2);
return implode(':', $chunks);
}