feat: Implement directory validation and shell command quoting
- Added is_valid_directory function to validate directory paths, ensuring they do not contain control characters and are within a specified length. - Introduced quote_shell_arg to safely quote shell arguments, preventing command injection. - Created build_cd_command to generate a command for changing directories in a shell. - Enhanced the LoginHandler to utilize a login rate limiter, preventing brute-force attacks by tracking failed login attempts. - Implemented an EncodingCache to optimize encoding detection for SSH connections. - Updated the UI to include an input field for specifying an initial directory upon login, with appropriate validation and hints. - Added a quickbar in the terminal interface for easy access to copy and paste functionality. - Introduced a toast notification system to provide feedback on copy actions. - Refactored connection storage to encrypt passwords at rest, improving security. - Updated various templates and styles to accommodate new features and improve user experience.
This commit is contained in:
+243
-5
@@ -8,7 +8,7 @@ from tests.utils import read_file, make_tests_data_path
|
||||
from webssh import handler
|
||||
from webssh import worker
|
||||
from webssh.handler import (
|
||||
IndexHandler, MixinHandler, WsockHandler, PrivateKey, InvalidValueError, SSHClient
|
||||
IndexHandler, MixinHandler, WsockHandler, PrivateKey, InvalidValueError, SSHClient, LoginRateLimiter, EncodingCache
|
||||
)
|
||||
|
||||
try:
|
||||
@@ -324,6 +324,7 @@ class TestIndexHandler(unittest.TestCase):
|
||||
obj.get_port.return_value = 22
|
||||
obj.get_value.return_value = 'root'
|
||||
obj.get_privatekey.return_value = ('', '')
|
||||
obj.get_directory.return_value = ''
|
||||
obj.policy = paramiko.WarningPolicy()
|
||||
obj.ssh_client = Mock()
|
||||
|
||||
@@ -345,16 +346,75 @@ class TestIndexHandler(unittest.TestCase):
|
||||
)
|
||||
self.assertEqual('root-secret', obj.connection_info['password'])
|
||||
|
||||
def test_get_args_carries_directory(self):
|
||||
obj = Mock(spec=IndexHandler)
|
||||
obj.get_hostname.return_value = '127.0.0.1'
|
||||
obj.get_port.return_value = 22
|
||||
obj.get_value.return_value = 'root'
|
||||
obj.get_privatekey.return_value = ('', '')
|
||||
obj.get_directory.return_value = '/var/www'
|
||||
obj.policy = paramiko.WarningPolicy()
|
||||
obj.ssh_client = Mock()
|
||||
obj.get_argument.side_effect = lambda name, default=u'': default
|
||||
|
||||
args = IndexHandler.get_args(obj)
|
||||
|
||||
self.assertEqual('/var/www', args[6])
|
||||
self.assertEqual('/var/www', obj.connection_info['directory'])
|
||||
|
||||
def test_get_directory(self):
|
||||
obj = Mock(spec=IndexHandler)
|
||||
values = {}
|
||||
obj.get_argument.side_effect = lambda name, default=u'': values.get(
|
||||
name, default
|
||||
)
|
||||
|
||||
self.assertEqual('', IndexHandler.get_directory(obj))
|
||||
|
||||
values['directory'] = ' '
|
||||
self.assertEqual('', IndexHandler.get_directory(obj))
|
||||
|
||||
values['directory'] = ' /var/www '
|
||||
self.assertEqual('/var/www', IndexHandler.get_directory(obj))
|
||||
|
||||
values['directory'] = '/tmp\nrm -rf /'
|
||||
with self.assertRaises(InvalidValueError):
|
||||
IndexHandler.get_directory(obj)
|
||||
|
||||
values['directory'] = '/tmp' + 'a' * 1024
|
||||
with self.assertRaises(InvalidValueError):
|
||||
IndexHandler.get_directory(obj)
|
||||
|
||||
def test_change_directory_quotes_the_path(self):
|
||||
obj = Mock(spec=IndexHandler)
|
||||
chan = Mock()
|
||||
|
||||
IndexHandler.change_directory(obj, chan, '/tmp; reboot')
|
||||
|
||||
chan.sendall.assert_called_with(b"cd '/tmp; reboot'\r")
|
||||
|
||||
def test_change_directory_swallows_channel_errors(self):
|
||||
obj = Mock(spec=IndexHandler)
|
||||
chan = Mock()
|
||||
chan.sendall.side_effect = paramiko.SSHException('boom')
|
||||
|
||||
# a failed cd must not prevent the session from starting
|
||||
IndexHandler.change_directory(obj, chan, '/var/www')
|
||||
|
||||
def test_null_in_encoding(self):
|
||||
handler = Mock(spec=IndexHandler)
|
||||
mock_handler = Mock(spec=IndexHandler)
|
||||
|
||||
# This is a little nasty, but the index handler has a lot of
|
||||
# dependencies to mock. Mocking out everything but the bits
|
||||
# we want to test lets us test this case without needing to
|
||||
# refactor the relevant code out of IndexHandler
|
||||
def parse_encoding(data):
|
||||
return IndexHandler.parse_encoding(handler, data)
|
||||
handler.parse_encoding = parse_encoding
|
||||
return IndexHandler.parse_encoding(mock_handler, data)
|
||||
mock_handler.parse_encoding = parse_encoding
|
||||
|
||||
def detect_encoding(ssh):
|
||||
return IndexHandler.detect_encoding(mock_handler, ssh)
|
||||
mock_handler.detect_encoding = detect_encoding
|
||||
|
||||
ssh = Mock(spec=SSHClient)
|
||||
stdin = io.BytesIO()
|
||||
@@ -362,6 +422,184 @@ class TestIndexHandler(unittest.TestCase):
|
||||
stderr = io.BytesIO()
|
||||
ssh.exec_command.return_value = (stdin, stdout, stderr)
|
||||
|
||||
encoding = IndexHandler.get_default_encoding(handler, ssh)
|
||||
self.assertIsNone(IndexHandler.detect_encoding(mock_handler, ssh))
|
||||
|
||||
encoding = IndexHandler.get_default_encoding(mock_handler, ssh)
|
||||
self.assertEqual("utf-8", encoding)
|
||||
|
||||
|
||||
class TestLoginRateLimiter(unittest.TestCase):
|
||||
|
||||
def test_blocks_after_too_many_failures(self):
|
||||
limiter = LoginRateLimiter(max_attempts=3, window=300)
|
||||
|
||||
self.assertFalse(limiter.is_blocked('1.1.1.1'))
|
||||
for _ in range(2):
|
||||
limiter.record_failure('1.1.1.1')
|
||||
self.assertFalse(limiter.is_blocked('1.1.1.1'))
|
||||
|
||||
limiter.record_failure('1.1.1.1')
|
||||
self.assertTrue(limiter.is_blocked('1.1.1.1'))
|
||||
|
||||
# other clients are unaffected
|
||||
self.assertFalse(limiter.is_blocked('2.2.2.2'))
|
||||
|
||||
def test_success_resets_the_counter(self):
|
||||
limiter = LoginRateLimiter(max_attempts=2, window=300)
|
||||
|
||||
limiter.record_failure('1.1.1.1')
|
||||
limiter.record_failure('1.1.1.1')
|
||||
self.assertTrue(limiter.is_blocked('1.1.1.1'))
|
||||
|
||||
limiter.reset('1.1.1.1')
|
||||
self.assertFalse(limiter.is_blocked('1.1.1.1'))
|
||||
|
||||
def test_entries_expire_after_the_window(self):
|
||||
limiter = LoginRateLimiter(max_attempts=1, window=300)
|
||||
|
||||
limiter.record_failure('1.1.1.1')
|
||||
self.assertTrue(limiter.is_blocked('1.1.1.1'))
|
||||
|
||||
# pretend the failure happened longer ago than the window
|
||||
count, last = limiter.attempts['1.1.1.1']
|
||||
limiter.attempts['1.1.1.1'] = (count, last - 301)
|
||||
|
||||
self.assertFalse(limiter.is_blocked('1.1.1.1'))
|
||||
self.assertEqual({}, limiter.attempts)
|
||||
|
||||
def test_clear(self):
|
||||
limiter = LoginRateLimiter(max_attempts=1, window=300)
|
||||
|
||||
limiter.record_failure('1.1.1.1')
|
||||
self.assertTrue(limiter.is_blocked('1.1.1.1'))
|
||||
limiter.clear()
|
||||
self.assertFalse(limiter.is_blocked('1.1.1.1'))
|
||||
|
||||
|
||||
class TestEncodingCache(unittest.TestCase):
|
||||
|
||||
def test_get_and_set(self):
|
||||
cache = EncodingCache()
|
||||
|
||||
self.assertIsNone(cache.get(('127.0.0.1', 22)))
|
||||
cache.set(('127.0.0.1', 22), 'GBK')
|
||||
self.assertEqual('GBK', cache.get(('127.0.0.1', 22)))
|
||||
# the port is part of the key
|
||||
self.assertIsNone(cache.get(('127.0.0.1', 2200)))
|
||||
|
||||
def test_a_failed_probe_is_not_cached(self):
|
||||
cache = EncodingCache()
|
||||
|
||||
cache.set(('127.0.0.1', 22), None)
|
||||
cache.set(('127.0.0.1', 22), '')
|
||||
self.assertIsNone(cache.get(('127.0.0.1', 22)))
|
||||
|
||||
def test_cache_is_bounded(self):
|
||||
cache = EncodingCache(maxsize=2)
|
||||
|
||||
cache.set(('a', 22), 'UTF-8')
|
||||
cache.set(('b', 22), 'UTF-8')
|
||||
cache.set(('c', 22), 'UTF-8')
|
||||
self.assertEqual(1, len(cache.cache))
|
||||
self.assertEqual('UTF-8', cache.get(('c', 22)))
|
||||
|
||||
|
||||
class TestGetEncoding(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
handler.encoding_cache.clear()
|
||||
self.addCleanup(handler.encoding_cache.clear)
|
||||
|
||||
def make_handler(self, detected):
|
||||
obj = Mock(spec=IndexHandler)
|
||||
obj.detect_encoding.return_value = detected
|
||||
return obj
|
||||
|
||||
def test_probes_once_then_serves_from_cache(self):
|
||||
obj = self.make_handler('GBK')
|
||||
ssh = Mock()
|
||||
dst_addr = ('127.0.0.1', 22)
|
||||
|
||||
self.assertEqual('GBK', IndexHandler.get_encoding(obj, ssh, dst_addr))
|
||||
self.assertEqual('GBK', IndexHandler.get_encoding(obj, ssh, dst_addr))
|
||||
self.assertEqual(1, obj.detect_encoding.call_count)
|
||||
|
||||
def test_failed_detection_falls_back_without_caching(self):
|
||||
obj = self.make_handler(None)
|
||||
ssh = Mock()
|
||||
dst_addr = ('127.0.0.1', 22)
|
||||
|
||||
self.assertEqual(
|
||||
'utf-8', IndexHandler.get_encoding(obj, ssh, dst_addr)
|
||||
)
|
||||
self.assertEqual(
|
||||
'utf-8', IndexHandler.get_encoding(obj, ssh, dst_addr)
|
||||
)
|
||||
self.assertEqual(2, obj.detect_encoding.call_count)
|
||||
|
||||
|
||||
class TestClientKey(unittest.TestCase):
|
||||
|
||||
def make_handler(self, auth_manager, addr=('10.0.0.1', 1234)):
|
||||
obj = Mock(spec=MixinHandler)
|
||||
obj.auth_manager = auth_manager
|
||||
obj.get_client_addr.return_value = addr
|
||||
return obj
|
||||
|
||||
def test_logged_in_users_get_their_own_bucket(self):
|
||||
alice = self.make_handler(Mock())
|
||||
alice.current_user = 'alice'
|
||||
bob = self.make_handler(Mock())
|
||||
bob.current_user = 'bob'
|
||||
|
||||
# same source address, different buckets
|
||||
self.assertEqual('user:alice', MixinHandler.get_client_key(alice))
|
||||
self.assertEqual('user:bob', MixinHandler.get_client_key(bob))
|
||||
|
||||
def test_without_auth_the_address_is_used(self):
|
||||
obj = self.make_handler(None)
|
||||
self.assertEqual('10.0.0.1', MixinHandler.get_client_key(obj))
|
||||
|
||||
def test_a_username_cannot_collide_with_an_address(self):
|
||||
spoofer = self.make_handler(Mock())
|
||||
spoofer.current_user = '10.0.0.1'
|
||||
|
||||
direct = self.make_handler(None)
|
||||
|
||||
self.assertNotEqual(
|
||||
MixinHandler.get_client_key(spoofer),
|
||||
MixinHandler.get_client_key(direct)
|
||||
)
|
||||
|
||||
|
||||
class TestClearWorker(unittest.TestCase):
|
||||
|
||||
def make_worker(self, worker_id, client_key):
|
||||
obj = Mock()
|
||||
obj.id = worker_id
|
||||
obj.client_key = client_key
|
||||
return obj
|
||||
|
||||
def test_removes_the_worker_and_prunes_empty_buckets(self):
|
||||
a = self.make_worker('a', 'user:admin')
|
||||
b = self.make_worker('b', 'user:admin')
|
||||
clients = {'user:admin': {'a': a, 'b': b}}
|
||||
|
||||
worker.clear_worker(a, clients)
|
||||
self.assertEqual({'user:admin': {'b': b}}, clients)
|
||||
|
||||
worker.clear_worker(b, clients)
|
||||
self.assertEqual({}, clients)
|
||||
|
||||
def test_unregistered_worker_is_ignored(self):
|
||||
orphan = self.make_worker('a', None)
|
||||
clients = {}
|
||||
|
||||
# must not raise even though the worker was never registered
|
||||
worker.clear_worker(orphan, clients)
|
||||
self.assertEqual({}, clients)
|
||||
|
||||
clients = {'user:admin': {'b': 'other'}}
|
||||
orphan.client_key = 'user:admin'
|
||||
worker.clear_worker(orphan, clients)
|
||||
self.assertEqual({'user:admin': {'b': 'other'}}, clients)
|
||||
|
||||
Reference in New Issue
Block a user