python-keyring-lib / keyring / backend.py

  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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
"""
backend.py

Created by Kang Zhang on 2009-07-09
"""

import base64
import hashlib
import os
import sys
import ConfigParser

from keyring.util.escape import escape as escape_for_ini

try:
    from abc import ABCMeta, abstractmethod
except ImportError:
    # to keep compatible with older Python versions.
    class ABCMeta(type):
        pass

    def abstractmethod(funcobj):
        return funcobj

try:
    import gnomekeyring
except ImportError:
    pass

_KEYRING_SETTING = 'keyring-setting'
_CRYPTED_PASSWORD = 'crypted-password'
_BLOCK_SIZE = 32
_PADDING = '0'

class PasswordSetError(Exception):
    """Raised when the password can't be set.
    """

class KeyringBackend(object):
    """The abstract base class of the keyring, every backend must implement
    this interface.
    """
    __metaclass__ = ABCMeta

    @abstractmethod
    def supported(self):
        """Return if this keyring supports current enviroment.
        -1: not applicable
         0: suitable
         1: recommended
        """
        return -1

    @abstractmethod
    def get_password(self, service, username):
        """Get password of the username for the service
        """
        return None

    @abstractmethod
    def set_password(self, service, username, password):
        """Set password for the username of the service
        """
        raise PasswordSetError()

class _ExtensionKeyring(KeyringBackend):
    """_ExtensionKeyring is a adaptor class for the platform related keyring
    backends.
    """
    def __init__(self):
        try:
            self.keyring_impl = self._init_backend()
        except ImportError:
            # keyring is not installed properly
            self.keyring_impl = None

    def _init_backend(self):
        """Return the keyring implementation handler
        """
        return None

    def _recommend(self):
        """If this keyring is recommanded on current enviroment.
        """
        return False

    def supported(self):
        """Override the supported() in KeyringBackend.
        """
        if self.keyring_impl is None:
            return -1
        elif self._recommend():
            return 1
        return 0

    def get_password(self, service, username):
        """Override the get_password() in KeyringBackend.
        """
        try:
            password = self.keyring_impl.password_get(service, username)
        except OSError:
            password = None
        return password

    def set_password(self, service, username, password):
        """Overide the set_password() in KeyringBackend.
        """
        try:
            self.keyring_impl.password_set(service, username, password)
        except OSError:
            raise PasswordSetError()

class OSXKeychain(_ExtensionKeyring):
    """Mac OSX Keychain"""
    def _init_backend(self):
        """Return the handler: osx_keychain
        """
        import osx_keychain
        return osx_keychain

    def _recommend(self):
        """Recommend for all OSX enviroment.
        """
        return sys.platform == 'darwin'

class GnomeKeyring(KeyringBackend):
    """Gnome Keyring"""

    def supported(self):
        try:
            import gnomekeyring
        except ImportError:
            return -1
        else:
            if os.environ.has_key("GNOME_KEYRING_CONTROL"):
                return 1
            else:
                return 0

    def get_password(self, service, username):
        """Get password of the username for the service
        """
        try:
            items = gnomekeyring.find_network_password_sync(username, service)
        except gnomekeyring.NoMatchError:
            return None
        except gnomekeyring.CancelledError:
            # The user pressed "Cancel" when prompted to unlock their keyring.
            return None

        assert len(items) == 1, 'no more than one entry should ever match'
        return items[0]['password']

    def set_password(self, service, username, password):
        """Set password for the username of the service
        """
        try:
            gnomekeyring.set_network_password_sync(None, username, service,
                None, None, None, None, 0, password)
        except gnomekeyring.CancelledError:
            # The user pressed "Cancel" when prompted to unlock their keyring.
            raise PasswordSetError()

kwallet = None

def open_kwallet(kwallet_module=None, qt_module=None):

    global kwallet
    if not kwallet is None:
        return kwallet

    # Allow for the injection of module-like objects for testing purposes.
    if kwallet_module is None:
        kwallet_module = KWallet.Wallet
    if qt_module is None:
        qt_module = QtGui

    # KDE wants us to instantiate an application object.
    app = None
    if qt_module.qApp.instance() == None:
        app = qt_module.QApplication([])
    try:
        window = qt_module.QWidget()
        kwallet = kwallet_module.openWallet(
            kwallet_module.NetworkWallet(),
            window.winId(),
            kwallet_module.Synchronous)
        if kwallet is not None:
            if not kwallet.hasFolder('Python'):
                kwallet.createFolder('Python')
            kwallet.setFolder('Python')
            return kwallet
    finally:
        if app:
            app.exit()


try:
    from PyKDE4.kdeui import KWallet
    from PyQt4 import QtGui
except ImportError:
    kwallet_support = False
else:
    kwallet_support = True


class KDEKWallet(KeyringBackend):
    """KDE KWallet"""

    def supported(self):
        if kwallet_support and os.environ.has_key('KDE_SESSION_UID'):
            return 1
        elif kwallet_support:
            return 0
        else:
            return -1

    def get_password(self, service, username):
        """Get password of the username for the service
        """
        key = username + '@' + service
        network = KWallet.Wallet.NetworkWallet()
        wallet = open_kwallet()
        if wallet.keyDoesNotExist(network, 'Python', key):
            return None

        result = wallet.readPassword(key)[1]
        # The string will be a PyQt4.QtCore.QString, so turn it into a unicode
        # object.
        return unicode(result)

    def set_password(self, service, username, password):
        """Set password for the username of the service
        """
        wallet=open_kwallet()
        wallet.writePassword(username+'@'+service, password)

class BasicFileKeyring(KeyringBackend):
    """BasicFileKeyring is a filebased implementation of keyring.

    It stores the password directly in the file, and supports the
    encryption and decryption. The encrypted password is stroed in base64
    format.
    """

    def __init__(self):
        self.file_path = os.path.join(os.path.expanduser("~"), self.filename())

    @abstractmethod
    def filename(self):
        """Return the filename used to store the passwords.
        """
        pass

    @abstractmethod
    def encrypt(self, password):
        """Encrypt the password.
        """
        pass

    @abstractmethod
    def decrypt(self, password_encrypted):
        """Decrypt the password.
        """
        pass

    def get_password(self, service, username):
        """Read the password from the file.
        """
        service = escape_for_ini(service)
        username = escape_for_ini(username)

        # load the passwords from the file
        config = ConfigParser.RawConfigParser()
        if os.path.exists(self.file_path):
            config.read(self.file_path)

        # fetch the password
        try:
            password_base64 = config.get(service, username)
            # decode with base64
            password_encrypted = password_base64.decode("base64")
            # decrypted the password
            password = self.decrypt(password_encrypted)
        except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
            password = None
        return password

    def set_password(self, service, username, password):
        """Write the password in the file.
        """
        service = escape_for_ini(service)
        username = escape_for_ini(username)

        # encrypt the password
        password_encrypted = self.encrypt(password)
        # load the password from the disk
        config = ConfigParser.RawConfigParser()
        if os.path.exists(self.file_path):
            config.read(self.file_path)

        # encode with base64
        password_base64 = password_encrypted.encode("base64")
        # write the modification
        if not config.has_section(service):
            config.add_section(service)
        config.set(service, username, password_base64)
        config_file = open(self.file_path,'w')
        config.write(config_file)

class UncryptedFileKeyring(BasicFileKeyring):
    """Uncrypted File Keyring"""
    def filename(self):
        """Return the filename of the password file. It should be
        "keyring_pass.cfg" .
        """
        return "keyring_pass.cfg"

    def encrypt(self, password):
        """Directly return the password itself.
        """
        return password

    def decrypt(self, password_encrypted):
        """Directly return encrypted password.
        """
        return password_encrypted

    def supported(self):
        """Applicable for all platforms, but do not recommend.
        """
        return 0

class CryptedFileKeyring(BasicFileKeyring):
    """PyCrypto File Keyring"""
    def __init__(self):
        super(CryptedFileKeyring, self).__init__()
        self.crypted_password = None

    def filename(self):
        """Return the filename for the password file.
        """
        return "crypted_pass.cfg"

    def supported(self):
        """Applicable for all platforms, but not recommend
        """
        try:
            from Crypto.Cipher import AES
            status = 0
        except ImportError:
            status = -1
        return status

    def _init_file(self):
        """Init the password file, set the password for it."""

        print("Please set a password for your new keyring")
        password = None
        while 1:
            if not password:
                import getpass
                password = getpass.getpass()
                password2 = getpass.getpass('Password (again): ')
                if password != password2:
                    sys.stderr.write("Error: Your passwords didn't math\n")
                    password = None
                    continue
            if '' == password.strip():
                # forbid the blank password
                sys.stderr.write("Error: blank passwords aren't allowed.\n")
                password = None
                continue
            if len(password) > _BLOCK_SIZE:
                # block size of AES is less than 32
                sys.stderr.write("Error: password can't be longer than 32.\n")
                password = None
                continue
            break

        # hash the password
        import crypt
        self.crypted_password = crypt.crypt(password, password)

        # write down the initialization
        config = ConfigParser.RawConfigParser()
        config.add_section(_KEYRING_SETTING)
        config.set(_KEYRING_SETTING, _CRYPTED_PASSWORD, self.crypted_password)

        config_file = open(self.file_path,'w')
        config.write(config_file)

        if config_file:
            config_file.close()

    def _check_file(self):
        """Check if the password file has been init properly.
        """
        if os.path.exists(self.file_path):
            config = ConfigParser.RawConfigParser()
            config.read(self.file_path)
            try:
                self.crypted_password = config.get(_KEYRING_SETTING,
                                                    _CRYPTED_PASSWORD)
                return self.crypted_password.strip() != ''
            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                pass
        return False

    def _auth(self, password):
        """Return if the password can open the keyring.
        """
        import crypt
        return crypt.crypt(password, password) == self.crypted_password

    def _init_crypter(self):
        """Init the crypter(using the password of the keyring).
        """
        # check the password file
        if not self._check_file():
            self._init_file()

        print "Please input your password for the keyring"
        import getpass
        password = getpass.getpass()

        if not self._auth(password):
            sys.stderr.write("Wrong password for the keyring.\n")
            raise ValueError("Wrong password")

        # init the cipher with the password
        from Crypto.Cipher import AES
        # pad to _BLOCK_SIZE bytes
        password = password + (_BLOCK_SIZE - len(password) % _BLOCK_SIZE) * \
                                                                    _PADDING
        return AES.new(password, AES.MODE_CFB)

    def encrypt(self, password):
        """Encrypt the given password using the pycryto.
        """
        crypter = self._init_crypter()
        return crypter.encrypt(password)

    def decrypt(self, password_encrypted):
        """Decrypt the given password using the pycryto.
        """
        crypter = self._init_crypter()
        return crypter.decrypt(password_encrypted)

class AgentEncryptedKeyring(BasicFileKeyring):
    def __init__(self):
        super(AgentEncryptedKeyring, self).__init__()
        import Crypto, getpass
        setattr(self, "Crypto", Crypto)
        setattr(self, "getpass", getpass)
        self.clear_passphrase = None

        self.config = ConfigParser.RawConfigParser()
        if os.path.exists(self.file_path):
            self.config.read(self.file_path)
        else:
            self._initialize_configuration()

        import paramiko
        self.agent = paramiko.Agent()

    def _hash_passphrase(self, passphrase):
        sha = hashlib.sha256()
        sha.update(passphrase)
        hashed_passphrase = base64.encodestring(sha.digest()).strip()
        return hashed_passphrase

    def _initialize_configuration(self):
        while self.clear_passphrase is None:
            import getpass
            passphrase = getpass.getpass("Configure a passphrase: ")
            passphrase2 = getpass.getpass("Confirm your passphrase: ")
            if passphrase != passphrase2:
                print "The passphrases didn't match."
            else:
                self.clear_passphrase = passphrase
                hashed_passphrase = self._hash_passphrase(passphrase)
                self.config.add_section("keyring_credentials")
                self.config.set("keyring_credentials",
                                "passphrase",
                                hashed_passphrase)
        self.write_configuration()

    def _retrieve_passphrase(self):
        for ssh_key in self.agent.keys:
            fingerprint = ''.join(["%02x" % ord(c) for c in ssh_key.get_fingerprint()])
            if self.config.has_option("keyring_credentials",
                                      fingerprint):
                encrypted_passphrase = self.config.get("keyring_credentials",
                                                       fingerprint)

                aes_key = ssh_key.sign_ssh_data(None, ssh_key.get_fingerprint())[-32:]
                aes = self.Crypto.Cipher.AES.new(aes_key)
                passphrase = aes.decrypt(base64.decodestring(encrypted_passphrase))
                passphrase = passphrase.replace('\x00', '')
                hashed_passphrase = self._hash_passphrase(passphrase)

                if hashed_passphrase != self.config.get("keyring_credentials",
                                                        "passphrase"):
                    print "Passphrase mismatch for key %s" % fingerprint
                else:
                    self.clear_passphrase = passphrase.strip()

        while self.clear_passphrase is None:
            passphrase = self.getpass.getpass("Please enter keyring passphrase: ")
            hashed_passphrase = self._hash_passphrase(passphrase)
            if hashed_passphrase != self.config.get("keyring_credentials",
                                                    "passphrase"):
                print "Passphrase mismatch"
            else:
                self.clear_passphrase = passphrase.strip()

        self._add_authorized_keys()
            
    def _add_authorized_keys(self):
        padded_passphrase = self.padded_passphrase

        for ssh_key in self.agent.keys:
            fingerprint = ''.join(["%02x" % ord(c) for c in ssh_key.get_fingerprint()])
            if not self.config.has_option("keyring_credentials",
                                          fingerprint):
                print "Authorize %s to unlock this keyring? (y/N): "  % fingerprint,
                response = sys.stdin.readline().strip()
                if response.upper() == 'Y':
                    aes_key = ssh_key.sign_ssh_data(None, ssh_key.get_fingerprint())[-32:]
                    aes = self.Crypto.Cipher.AES.new(aes_key)
                    encrypted_passphrase = base64.encodestring(aes.encrypt(padded_passphrase)).strip()
                    self.config.set("keyring_credentials", 
                                    fingerprint, 
                                    encrypted_passphrase)
                    
                    self.write_configuration()
                    

    @property
    def cipher(self):
        return self.Crypto.Cipher.AES.new(self.padded_passphrase)

    def decrypt(self, encrypted):
        return self.cipher.decrypt(base64.decodestring(encrypted)).replace('\x00', '')

    def encrypt(self, password):
        return base64.encodestring(self.cipher.encrypt(self.pad_string(password)))

    def filename(self):
        return ".agent_encrypted_keyring.cfg"

    def pad_string(self, to_pad):
        if len(to_pad) > 16:
            pad_length = (((len(to_pad) / 16) + 1) * 16) - len(to_pad)
        else:
            pad_length = 16 - len(to_pad)
            
        return to_pad + ("\x00" * pad_length)

    @property
    def padded_passphrase(self):
        if self.passphrase is None:
            raise Exception("Passphrase is not available")

        return self.pad_string(self.passphrase)

    @property
    def passphrase(self):
        if self.clear_passphrase is None:
            self._retrieve_passphrase()
        return self.clear_passphrase

    def supported(self):
        """Acceptable on any platform with an SSH Agent,
        preferable when keys exist"""
        try:
            from Crypto.Cipher import AES
        except ImportError:
            return -1

        try:
            import paramiko
            agent = paramiko.Agent()
            if len(agent.keys):
                return 1
            else:
                return 0
        except ImportError:
            return -1
            
    def write_configuration(self):
        config_file = open(self.file_path, 'w')
        self.config.write(config_file)

        if config_file:
            config_file.close()

class Win32CryptoKeyring(BasicFileKeyring):
    """Win32 Cryptography Keyring"""
    def __init__(self):
        super(Win32CryptoKeyring, self).__init__()

        try:
            import win32_crypto
            self.crypt_handler = win32_crypto
        except ImportError:
            self.crypt_handler = None

    def filename(self):
        """Return the filename for the password storages file.
        """
        return "wincrypto_pass.cfg"

    def supported(self):
        """Recommend when other Windows backends are unavailable
        """
        recommended = select_windows_backend()
        if recommended == None:
            return -1
        elif recommended == 'file':
            return 1
        else:
            return 0

    def encrypt(self, password):
        """Encrypt the password using the CryptAPI.
        """
        return self.crypt_handler.encrypt(password)

    def decrypt(self, password_encrypted):
        """Decrypt the password using the CryptAPI.
        """
        return self.crypt_handler.decrypt(password_encrypted)


class WinVaultKeyring(KeyringBackend):
    def __init__(self):
        super(WinVaultKeyring, self).__init__()
        try:
            import pywintypes, win32cred
            self.win32cred = win32cred
            self.pywintypes = pywintypes
        except ImportError:
            self.win32cred = None
    
    def supported(self):
        '''Default Windows backend, when it is available
        '''
        recommended = select_windows_backend()
        if recommended == None:
            return -1
        elif recommended == 'cred':
            return 1
        else:
            return 0
    
    def get_password(self, service, username):
        try:
            blob = self.win32cred.CredRead(Type=self.win32cred.CRED_TYPE_GENERIC, 
                                           TargetName=service)['CredentialBlob']
        except self.pywintypes.error, e:
            if e[:2] == (1168, 'CredRead'):
                return None
            raise
        return blob.decode("utf16")
    
    def set_password(self, service, username, password):
        credential = dict(Type=self.win32cred.CRED_TYPE_GENERIC, 
                          TargetName=service,
                          UserName=username,
                          CredentialBlob=unicode(password),
                          Comment="Stored using python-keyring",
                          Persist=self.win32cred.CRED_PERSIST_ENTERPRISE)
        self.win32cred.CredWrite(credential, 0)


class Win32CryptoRegistry(KeyringBackend):
    """Win32CryptoRegistry is a keyring which use Windows CryptAPI to encrypt
    the user's passwords and store them under registry keys
    """
    def __init__(self):
        super(Win32CryptoRegistry, self).__init__()

        try:
            import win32_crypto
            import _winreg
            self.crypt_handler = win32_crypto
        except ImportError:
            self.crypt_handler = None

    def supported(self):
        """Return if this keyring supports current enviroment.
        -1: not applicable
         0: suitable
         1: recommended
        """
        recommended = select_windows_backend()
        if recommended == None:
            return -1
        elif recommended == 'reg':
            return 1
        else:
            return 0

    def get_password(self, service, username):
        """Get password of the username for the service
        """
        from _winreg import HKEY_CURRENT_USER, OpenKey, QueryValueEx
        try:
            # fetch the password
            key = r'Software\%s\Keyring' % service
            hkey = OpenKey(HKEY_CURRENT_USER, key)
            password_base64 = QueryValueEx(hkey, username)[0]
            # decode with base64
            password_encrypted = password_base64.decode("base64")
            # decrypted the password
            password = self.crypt_handler.decrypt(password_encrypted)
        except EnvironmentError:
            password = None
        return password


    def set_password(self, service, username, password):
        """Write the password to the registry
        """
        # encrypt the password
        password_encrypted = self.crypt_handler.encrypt(password)
        # encode with base64
        password_base64 = password_encrypted.encode("base64")

        # store the password
        from _winreg import HKEY_CURRENT_USER, CreateKey, SetValueEx, REG_SZ
        hkey = CreateKey(HKEY_CURRENT_USER, r'Software\%s\Keyring' % service)
        SetValueEx(hkey, username, 0, REG_SZ, password_base64)

def select_windows_backend():
    if os.name != 'nt':
        return None
    major, minor, build, platform, text = sys.getwindowsversion()
    try:
        import pywintypes, win32cred
        if (major, minor) >= (5, 1):
            # recommend for windows xp+
            return 'cred'
    except ImportError:
        pass
    try:
        import win32_crypto, _winreg
        if (major, minor) >= (5, 0):
            # recommend for windows 2k+
            return 'reg'
    except ImportError:
        pass
    try:
        import win32_crypto
        return 'file'
    except ImportError:
        pass
    return None


_all_keyring = None

def get_all_keyring():
    """Return the list of all keyrings in the lib
    """
    global _all_keyring
    if _all_keyring is None:
        _all_keyring = [ OSXKeychain(), GnomeKeyring(), KDEKWallet(),
                         CryptedFileKeyring(), UncryptedFileKeyring(),
                         Win32CryptoKeyring(), Win32CryptoRegistry(),
                         WinVaultKeyring()]
    return _all_keyring
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.