Exemplo n.º 1
0
 def setUp(self):
     super(IDStrategyCase, self).setUp()
     self.group = Group(label='host_test')
     self.host = Host(label='host_test')
     self.sshconfig = SshConfig(port=2)
     self.identity = Identity(username='******')
     self.sshkey = SshKey(label='label')
Exemplo n.º 2
0
    def provider_hosts(self):
        """Retrieve SecureCRT sessions from xml config."""
        result_hosts = []
        tree = self.parser.parse_hosts()

        root_group = Group(label='SecureCRT')

        identity_paths = self.parser.parse_identity()
        if identity_paths:
            self.logger.info('Found private key path: %s', identity_paths[0])
            self.logger.info('Found public key path: %s', identity_paths[1])
            try:
                key = self.create_key(identity_paths)
                root_group.ssh_config = SshConfig(
                    identity=Identity(
                        ssh_key=key,
                        label='SecureCRT',
                        is_visible=False
                    )
                )
            except IOError:
                self.logger.info(
                    'Warning: cannot import SSH2 raw key %s',
                    identity_paths[1]
                )

        self.create_entries_from_tree(tree, result_hosts, root_group)
        self.logger.info('Parsed hosts %i', len(result_hosts))
        self.logger.info('Importing...')
        return result_hosts
Exemplo n.º 3
0
def test_single_sshconfig_with_fnmatch(mockpath):
    mockpath.return_value.open.return_value.__enter__.return_value = StringIO(
        """
Host ?i*one
    Port 2022

Host firstone
    HostName localhost
    User ubuntu
        """
    )
    service = SSHService(None, '')
    ssh_hosts = service.hosts()
    eq_(ssh_hosts, [
        Host(
            label='firstone',
            address='localhost',
            ssh_config=SshConfig(
                port=2022,
                timeout=None,
                keep_alive_packages=None,
                use_ssh_key=None,
                strict_host_key_check=None,
                identity=Identity(
                    username='******',
                    ssh_key=None
                )
            )
        )
    ])
Exemplo n.º 4
0
def test_single_sshconfig(mockpath):
    mockpath.return_value.open.return_value.__enter__.return_value = StringIO(
        """
Host firstone
    HostName localhost
    User ubuntu
    ServerAliveInterval 100
    ServerAliveCountMax 3
    IdentitiesOnly yes
    StrictHostKeyChecking no
        """
    )
    service = SSHService(None, '')
    ssh_hosts = service.hosts()
    eq_(ssh_hosts, [
        Host(
            label='firstone',
            address='localhost',
            ssh_config=SshConfig(
                port=None,
                timeout=100,
                keep_alive_packages=3,
                use_ssh_key=True,
                strict_host_key_check=False,
                identity=Identity(
                    username='******',
                    ssh_key=None
                )
            )
        )
    ])
Exemplo n.º 5
0
def test_single_sshconfig_with_keys(path_in_providers, path_in_adapters):
    sshconfig_content = """
Host firstone
    HostName localhost
    User ubuntu
    IdentityFile ~/.ssh/id_rsa
    IdentityFile ~/.ssh/id_dsa
    """
    private_key_content = 'private_key'
    fake_files = FakePathsObj(**{
        '~/.ssh/config': sshconfig_content,
        '~/.ssh/id_rsa': private_key_content
    })

    path_in_providers.side_effect = fake_files.generate_path_obj
    path_in_adapters.side_effect = fake_files.generate_path_obj

    service = SSHPortingProvider(None, '')
    ssh_hosts = service.provider_hosts()
    eq_(ssh_hosts, [
        Host(label='firstone',
             address='localhost',
             ssh_config=SshConfig(
                 port=None,
                 timeout=None,
                 keep_alive_packages=None,
                 use_ssh_key=None,
                 strict_host_key_check=None,
                 identity=Identity(username='******',
                                   ssh_key=SshKey(label='id_rsa',
                                                  private_key='private_key'))))
    ])
Exemplo n.º 6
0
    def adapt_ssh_config_host_to_instance(self,
                                          alias,
                                          parsed_host,
                                          parsed_group=None):
        """Convert parsed host to application host."""
        app_host = Host(
            label=alias,
            address=parsed_host['hostname'],
        )
        ssh_config = SshConfig(identity=Identity(
            username=parsed_host.get('user', self.default_user),
            ssh_key=self.create_key(parsed_host),
            is_visible=False,
            label=app_host.label))

        ssh_config.port = parsed_host.get('port')
        ssh_config.timeout = parsed_host.get('serveraliveinterval')
        ssh_config.keep_alive_packages = parsed_host.get('serveralivecountmax')
        ssh_config.use_ssh_key = parsed_host.get('identitiesonly')
        ssh_config.strict_host_key_check = parsed_host.get(
            'stricthostkeychecking')

        app_host.ssh_config = ssh_config
        if parsed_group:
            app_host.group = parsed_group

        return app_host
Exemplo n.º 7
0
    def test_create_transformer_nosync_key(self):
        self.account_manager.set_settings({
            'synchronize_key': False,
            'agent_forwarding': True
        })
        self.transformer = BulkTransformer(
            storage=self.storage,
            crypto_controller=self.crypto_controller,
            account_manager=self.account_manager,
        )

        ssh_config = SshConfig()
        identity = Identity(label='identity')
        ssh_key = SshKey(label='ssh_key')
        host = Host(label='host')
        identity.ssh_key = ssh_key.id = self.storage.save(ssh_key).id
        ssh_config.identity = identity.id = self.storage.save(identity).id
        host.ssh_config = ssh_config.id = self.storage.save(ssh_config).id
        host = self.storage.save(host)
        last_synced_data = dict(last_synced='')
        payload = self.transformer.to_payload(last_synced_data)
        self.assertEqual(
            payload, {
                'host_set':
                [{
                    'label': payload['host_set'][0]['label'],
                    'group': None,
                    'ssh_config': 'sshconfig_set/{}'.format(ssh_config.id),
                    'local_id': host.id,
                    'address': '',
                    'interaction_date': host.interaction_date,
                }],
                'sshconfig_set': [{
                    'font_size': None,
                    'keep_alive_packages': None,
                    'charset': None,
                    'local_id': ssh_config.id,
                    'use_ssh_key': None,
                    'timeout': None,
                    'color_scheme': None,
                    'is_forward_ports': None,
                    'strict_host_key_check': None,
                    'port': None,
                    'startup_snippet': None,
                    'cursor_blink': None
                }],
                'snippet_set': [],
                'last_synced':
                '',
                'group_set': [],
                'tag_set': [],
                'taghost_set': [],
                'pfrule_set': [],
                'delete_sets': {},
            })
        eq_(host.label, self.cryptor.decrypt(payload['host_set'][0]['label']))
Exemplo n.º 8
0
    def adapt_ssh_config_host_to_instance(self, alias, parsed_host):
        """Convert parsed host to application host."""
        app_host = Host(
            label=alias,
            address=parsed_host['hostname'],
        )
        ssh_config = SshConfig(
            identity=Identity(
                username=parsed_host.get('user', self.default_user),
                ssh_key=self.create_key(parsed_host),
                is_visible=False,
                label=app_host.label
            )
        )

        ssh_config.port = parsed_host.get('port')
        ssh_config.timeout = parsed_host.get('serveraliveinterval')
        ssh_config.keep_alive_packages = parsed_host.get('serveralivecountmax')
        ssh_config.use_ssh_key = parsed_host.get('identitiesonly')
        ssh_config.strict_host_key_check = parsed_host.get(
            'stricthostkeychecking'
        )

        app_host.ssh_config = ssh_config

        return app_host
Exemplo n.º 9
0
    def create_host(self, raw_host, group):
        """Create instances from groups tree."""
        host = Host(label=raw_host['label'],
                    address=raw_host['hostname'],
                    group=group)
        host.ssh_config = SshConfig(port=raw_host['port'])

        if raw_host['username']:
            identity = Identity(username=raw_host.get('username'),
                                is_visible=False,
                                label=raw_host.get('username'))

            host.ssh_config.identity = identity

        return host
Exemplo n.º 10
0
    def test_ssh2_identity_parsing(self):
        public_key = b'public'
        private_key = b'private'
        xml_path = '/some/path/securecrt.xml'

        root_group = Group(
            label='SecureCRT',
            ssh_config=SshConfig(
                identity=Identity(
                    label='SecureCRT',
                    is_visible=False,
                    ssh_key=SshKey(
                        label='SecureCRT',
                        private_key=private_key,
                        public_key=public_key
                    )
                )
            )
        )
        securecrt_config = """<?xml version="1.0" encoding="UTF-8"?>
            <VanDyke version="3.0">
                <key name="Sessions">
                    <key name="host0">
                        <dword name="[SSH2] Port">0</dword>
                        <string name="Hostname">addr0</string>
                        <string name="Username">user0</string>
                    </key>
                </key>
                <key name="SSH2">
                    <string name="Identity Filename V2">/Users/termius/folder/key.pub::rawkey</string>
                </key>
            </VanDyke>
            """
        expected = [
            Host(
                label='host0', group=root_group, address='addr0',
                ssh_config=SshConfig(port='0',
                    identity=Identity(
                        label='user0',
                        is_visible=False,
                        username='******'
                    )
                )
            )
        ]
        expected_calls = [
            call('/Users/termius/folder/key', 'rb'),
            call('/Users/termius/folder/key.pub', 'rb')
        ]

        with patch('xml.etree.ElementTree.open',
                   mock_open(read_data=securecrt_config)) as mocked_xml:

            with patch('termius.porting.providers.securecrt.provider.open',
                       mock_open(read_data='')) as mocked_open:
                service = SecureCRTPortingProvider(xml_path, None, '')
                mocked_open.side_effect = [
                    BytesIO(private_key), BytesIO(public_key)
                ]
                hosts = service.provider_hosts()
                self.assertEquals(
                    self.sort_hosts(hosts),
                    self.sort_hosts(expected)
                )
                mocked_xml.assert_called_once_with(xml_path, 'rb')
                mocked_open.assert_has_calls(expected_calls)
Exemplo n.º 11
0
    def test_tree_parsing(self):
        securecrt_config = """<?xml version="1.0" encoding="UTF-8"?>
    <VanDyke version="3.0">
        <key name="Sessions">
            <key name="host0">
                <dword name="[SSH2] Port">0</dword>
                <string name="Hostname">addr0</string>
                <string name="Username">user0</string>
            </key>
            <key name="hosts">
                <key name="folder0">
                    <key name="host1">
                        <dword name="[SSH2] Port">1</dword>
                        <string name="Hostname">addr1</string>
                        <string name="Username">user1</string>
                    </key>
                </key>
                <key name="folder1">
                    <key name="host2">
                        <dword name="[SSH2] Port">2</dword>
                        <string name="Hostname">addr2</string>
                        <string name="Username">user2</string>
                    </key>
                    <key name="serial">
                        <string name="Username">serial_user</string>
                    </key>
                </key>
            </key>
        </key>
    </VanDyke>
    """
        xml_path = '/some/path/securecrt.xml'
        root_group = Group(label='SecureCRT')
        hosts_folder = Group(
            label='hosts', parent_group=root_group
        )
        expected = [
            Host(
                label='host2',
                address='addr2',
                group=Group(label='folder1', parent_group=hosts_folder),
                ssh_config=SshConfig(
                    port='2',
                    identity=Identity(
                        label='user2', username='******', is_visible=False
                    )
                )
            ),
            Host(
                label='host1',
                address='addr1',
                group=Group(label='folder0', parent_group=hosts_folder),
                ssh_config=SshConfig(
                    port='1',
                    identity=Identity(
                        label='user1', username='******', is_visible=False
                    )
                )
            ),
            Host(
                label='host0', address='addr0', group=root_group,
                ssh_config=SshConfig(
                    port='0',
                    identity=Identity(
                        label='user0', username='******', is_visible=False
                    )
                )
            )
        ]

        with patch('xml.etree.ElementTree.open',
                   mock_open(read_data=securecrt_config)) as mocked_xml:
            service = SecureCRTPortingProvider(xml_path, None, '')
            hosts = service.provider_hosts()
            mocked_xml.assert_called_once_with(xml_path, 'rb')
            self.assertEquals(
                self.sort_hosts(hosts),
                self.sort_hosts(expected)
            )
Exemplo n.º 12
0
    def test_create_transformer_sync_key(self):
        self.transformer = self.get_transformer()

        ssh_config = SshConfig()
        identity = Identity(label='identity')
        ssh_key = SshKey(label='ssh_key')
        host = Host(label='host')
        identity.ssh_key = ssh_key.id = self.storage.save(ssh_key).id
        ssh_config.identity = identity.id = self.storage.save(identity).id
        host.ssh_config = ssh_config.id = self.storage.save(ssh_config).id
        host = self.storage.save(host)
        last_synced_data = dict(last_synced='')
        payload = self.transformer.to_payload(last_synced_data)
        self.assertEqual(
            payload, {
                'host_set':
                [{
                    'label': payload['host_set'][0]['label'],
                    'group': None,
                    'ssh_config': 'sshconfig_set/{}'.format(ssh_config.id),
                    'local_id': host.id,
                    'address': None,
                    'interaction_date': host.interaction_date,
                }],
                'sshconfig_set':
                [{
                    'font_size': None,
                    'keep_alive_packages': None,
                    'charset': None,
                    'identity': 'identity_set/{}'.format(identity.id),
                    'local_id': ssh_config.id,
                    'use_ssh_key': None,
                    'timeout': None,
                    'color_scheme': None,
                    'is_forward_ports': None,
                    'strict_host_key_check': None,
                    'port': None,
                    'startup_snippet': None,
                    'cursor_blink': None
                }],
                'snippet_set': [],
                'last_synced':
                '',
                'sshkeycrypt_set': [
                    {
                        'public_key': None,
                        'private_key': None,
                        'local_id': ssh_key.id,
                        'label': payload['sshkeycrypt_set'][0]['label']
                    }
                ],
                'group_set': [],
                'tag_set': [],
                'taghost_set': [],
                'pfrule_set': [],
                'delete_sets': {},
                'identity_set': [
                    {
                        'username': None,
                        'is_visible': None,
                        'ssh_key': 'sshkeycrypt_set/{}'.format(ssh_key.id),
                        'label': payload['identity_set'][0]['label'],
                        'local_id': identity.id
                    }
                ]
            })
        eq_(host.label, self.cryptor.decrypt(payload['host_set'][0]['label']))
        eq_(ssh_key.label,
            self.cryptor.decrypt(payload['sshkeycrypt_set'][0]['label']))
        eq_(identity.label,
            self.cryptor.decrypt(payload['identity_set'][0]['label']))