Пример #1
0
    def _create_new_identity(self):
        """
        Generate new Private key and new identity file.
        Reads some extra info from config files.
        """
        login = strng.to_bin(bpio.ReadTextFile(settings.UserNameFilename()))
        externalIP = strng.to_bin(misc.readExternalIP()) or b'127.0.0.1'
        if self.free_idurls[0].count(b'127.0.0.1'):
            externalIP = b'127.0.0.1'
        lg.out(
            4,
            'id_registrator._create_new_identity %s %s ' % (login, externalIP))

        my_id.forgetLocalIdentity()
        my_id.eraseLocalIdentity(do_backup=True)
        key.ForgetMyKey(erase_file=True, do_backup=True)
        key.InitMyKey()
        if not key.isMyKeyReady():
            key.GenerateNewKey()
        lg.out(4, '    my key is ready')
        ident = my_id.buildDefaultIdentity(name=login,
                                           ip=externalIP,
                                           idurls=self.free_idurls)
        my_identity_xmlsrc = ident.serialize(as_text=True)
        newfilename = settings.LocalIdentityFilename() + '.new'
        bpio.WriteTextFile(newfilename, my_identity_xmlsrc)
        try:
            id_url.identity_cached(ident)
        except:
            lg.exc()
        self.new_identity = ident
        lg.out(
            4, '    wrote %d bytes to %s' %
            (len(my_identity_xmlsrc), newfilename))
Пример #2
0
 def tearDown(self):
     backup_fs.shutdown()
     key.ForgetMyKey()
     my_id.forgetLocalIdentity()
     settings.shutdown()
     os.remove('/tmp/_some_priv_key')
     bpio.rmdir_recursive('/tmp/.bitdust_tmp')
Пример #3
0
 def tearDown(self):
     automat.CloseLogFile()
     tmpfile.shutdown()
     key.ForgetMyKey()
     my_id.forgetLocalIdentity()
     settings.shutdown()
     os.remove('/tmp/_some_priv_key')
     bpio.rmdir_recursive('/tmp/.bitdust_tmp')
     bpio.rmdir_recursive('/tmp/_some_folder')
     os.remove('/tmp/random_file')
Пример #4
0
 def tearDown(self):
     from main import settings
     from crypt import key
     from userid import my_id
     key.ForgetMyKey()
     my_id.forgetLocalIdentity()
     if os.path.isfile('/tmp/_current_localidentity'):
         os.rename('/tmp/_current_localidentity',
                   settings.LocalIdentityFilename())
     if os.path.isfile('/tmp/_current_priv_key'):
         os.rename('/tmp/_current_priv_key', settings.KeyFileName())
     os.remove('/tmp/_some_priv_key')
Пример #5
0
    def test_signed_key(self):
        try:
            bpio.rmdir_recursive('/tmp/.bitdust_test_signed_key')
        except Exception:
            pass
        lg.set_debug_level(30)
        settings.init(base_dir='/tmp/.bitdust_test_signed_key')
        self.my_current_key = None
        try:
            os.makedirs('/tmp/.bitdust_test_signed_key/metadata/')
        except:
            pass
        fout = open('/tmp/_some_priv_key', 'w')
        fout.write(_some_priv_key)
        fout.close()
        fout = open(settings.LocalIdentityFilename(), 'w')
        fout.write(_some_identity_xml)
        fout.close()
        self.assertTrue(key.LoadMyKey(keyfilename='/tmp/_some_priv_key'))
        self.assertTrue(my_id.loadLocalIdentity())

        key_id = '[email protected]_8084'
        my_keys.erase_key(key_id, keys_folder='/tmp/')
        my_keys.register_key(key_id, _sample_private_key, keys_folder='/tmp/')
        is_valid = my_keys.validate_key(my_keys.key_obj(key_id))
        self.assertTrue(is_valid)
        my_keys.sign_key(key_id)
        signed_key_info = my_keys.get_key_info(key_id,
                                               include_private=True,
                                               include_signature=True)
        self.assertTrue(my_keys.verify_key_info_signature(signed_key_info))

        key.ForgetMyKey()
        my_id.forgetLocalIdentity()
        settings.shutdown()
        os.remove('/tmp/_some_priv_key')
        bpio.rmdir_recursive('/tmp/.bitdust_test_signed_key')
Пример #6
0
def cmd_identity(opts, args, overDict, running):
    from userid import my_id
    from main import settings
    settings.init()
    my_id.init()

    if args[0] == 'idurl':
        if my_id.isLocalIdentityReady():
            print_text(my_id.getLocalID())
        else:
            print_text('local identity is not exist')
        return 0

    if len(args) == 1 or args[1].lower() in ['info', '?', 'show', 'print']:
        if my_id.isLocalIdentityReady():
            print_text(my_id.getLocalIdentity().serialize())
        else:
            print_text('local identity is not exist')
        return 0

    def _register():
        if len(args) <= 2:
            return 2
        pksize = settings.getPrivateKeySize()
        if len(args) > 3:
            try:
                pksize = int(args[3])
            except:
                print_text('incorrect private key size\n')
                return 0
        from automats import automat
        from main import initializer
        from lib import misc
        if not misc.ValidUserName(args[2]):
            return 0
        initializer.A('run-cmd-line-register', {'username': args[2], 'pksize': pksize})
        reactor.run()
        automat.objects().clear()
        if my_id.isLocalIdentityReady():
            print_text('new identity created:')
            print_text(my_id.getLocalIdentity().serialize())
        else:
            print_text('identity creation FAILED')
        return 0

    def _recover():
        from system import bpio
        from lib import nameurl
        if len(args) < 3:
            return 2
        src = bpio.ReadBinaryFile(args[2])
        if len(src) > 1024 * 10:
            print_text('file is too big for private key')
            return 0
        try:
            lines = src.split('\n')
            idurl = lines[0]
            txt = '\n'.join(lines[1:])
            if idurl != nameurl.FilenameUrl(nameurl.UrlFilename(idurl)):
                idurl = ''
                txt = src
        except:
            idurl = ''
            txt = src
        if idurl == '' and len(args) > 3:
            idurl = args[3]
        if idurl == '':
            print_text('BitDust need to know your IDURL to recover your account\n')
            return 2
        from automats import automat
        from main import initializer
        initializer.A('run-cmd-line-recover', {'idurl': idurl, 'keysrc': txt})
        reactor.run()
        automat.objects().clear()
        if my_id.isLocalIdentityReady():
            print_text('your identity were restored:')
            print_text(my_id.getLocalIdentity().serialize())
        else:
            print_text('identity recovery FAILED')
        return 0

    if args[1].lower() in ['create', 'new', 'register', 'generate', ]:
        if my_id.isLocalIdentityReady():
            print_text('local identity [%s] already exist\n' % my_id.getIDName())
            return 1
        if running:
            print_text('BitDust is running at the moment, need to stop the software at first\n')
            return 0
        return _register()

    if args[1].lower() in ['restore', 'recover', 'read', 'load', ]:
        if running:
            print_text('BitDust is running at the moment, need to stop the software at first\n')
            return 0
        return _recover()

    if args[1].lower() in ['delete', 'remove', 'erase', 'del', 'rm', 'kill']:
        if running:
            print_text('BitDust is running at the moment, need to stop the software at first\n')
            return 0
        oldname = my_id.getIDName()
        my_id.forgetLocalIdentity()
        my_id.eraseLocalIdentity()
        print_text('local identity [%s] is no longer exist\n' % oldname)
        return 0

    return 2
Пример #7
0
    def doVerifyAndRestore(self, *args, **kwargs):
        global _WorkingKey
        lg.out(4, 'identity_restorer.doVerifyAndRestore')

        remote_identity_src = args[0]

        if os.path.isfile(settings.KeyFileName()):
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore will backup and remove '
                + settings.KeyFileName())
            bpio.backup_and_remove(settings.KeyFileName())

        if os.path.isfile(settings.LocalIdentityFilename()):
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore will backup and remove '
                + settings.LocalIdentityFilename())
            bpio.backup_and_remove(settings.LocalIdentityFilename())

        try:
            remote_ident = identity.identity(xmlsrc=remote_identity_src)
            local_ident = identity.identity(xmlsrc=remote_identity_src)
        except:
            # lg.exc()
            reactor.callLater(0.1, self.automat, 'restore-failed',
                              ('remote identity have incorrect format',
                               'red'))  # @UndefinedVariable
            return

        lg.out(
            4, 'identity_restorer.doVerifyAndRestore checking remote identity')
        try:
            res = remote_ident.isCorrect()
        except:
            lg.exc()
            res = False
        if not res:
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore remote identity is not correct FAILED!!!!'
            )
            reactor.callLater(0.1, self.automat, 'restore-failed',
                              ('remote identity format is not correct',
                               'red'))  # @UndefinedVariable
            return

        lg.out(
            4, 'identity_restorer.doVerifyAndRestore validate remote identity')
        try:
            res = remote_ident.Valid()
        except:
            lg.exc()
            res = False
        if not res:
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore validate remote identity FAILED!!!!'
            )
            reactor.callLater(
                0.1, self.automat, 'restore-failed',
                ('remote identity is not valid', 'red'))  # @UndefinedVariable
            return

        my_id.forgetLocalIdentity()
        my_id.eraseLocalIdentity(do_backup=True)
        key.ForgetMyKey(erase_file=True, do_backup=True)
        bpio.WriteTextFile(settings.KeyFileName(), _WorkingKey)
        try:
            key.InitMyKey()
        except:
            key.ForgetMyKey(erase_file=True, do_backup=False)
            reactor.callLater(
                0.1, self.automat, 'restore-failed',
                ('private key is not valid', 'red'))  # @UndefinedVariable
            return

        try:
            local_ident.sign()
        except:
            # lg.exc()
            reactor.callLater(
                0.1, self.automat, 'restore-failed',
                ('error while signing identity', 'red'))  # @UndefinedVariable
            return

        if remote_ident.signature != local_ident.signature:
            reactor.callLater(
                0.1, self.automat, 'restore-failed',
                ('signature did not match, key verification failed!',
                 'red'))  # @UndefinedVariable
            return

        my_id.setLocalIdentity(local_ident)
        my_id.saveLocalIdentity()
        # my_id.rebuildLocalIdentity(save_identity=True)

        bpio.WriteTextFile(settings.UserNameFilename(), my_id.getIDName())

        if os.path.isfile(settings.KeyFileName() + '.backup'):
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore will remove backup file for '
                + settings.KeyFileName())
            bpio.remove_backuped_file(settings.KeyFileName())

        if os.path.isfile(settings.LocalIdentityFilename() + '.backup'):
            lg.out(
                4,
                'identity_restorer.doVerifyAndRestore will remove backup file for '
                + settings.LocalIdentityFilename())
            bpio.remove_backuped_file(settings.LocalIdentityFilename())

        reactor.callLater(0.1, self.automat,
                          'restore-success')  # @UndefinedVariable