Beispiel #1
0
 def _check_install(self):
     """
     Return True if Private Key and local identity files exists and both is
     valid.
     """
     if _Debug:
         lg.out(_DebugLevel, 'initializer._check_install')
     from userid import identity
     from crypt import key
     keyfilename = settings.KeyFileName()
     keyfilenamelocation = settings.KeyFileNameLocation()
     if os.path.exists(keyfilenamelocation):
         keyfilename = bpio.ReadTextFile(keyfilenamelocation)
         if not os.path.exists(keyfilename):
             keyfilename = settings.KeyFileName()
     idfilename = settings.LocalIdentityFilename()
     if not os.path.exists(keyfilename) or not os.path.exists(idfilename):
         if _Debug:
             lg.out(_DebugLevel, 'initializer._check_install local key or local id not exists')
         return False
     current_key = bpio.ReadTextFile(keyfilename)
     current_id = bpio.ReadTextFile(idfilename)
     if not current_id:
         if _Debug:
             lg.out(_DebugLevel, 'initializer._check_install local identity is empty ')
         return False
     if not current_key:
         if _Debug:
             lg.out(_DebugLevel, 'initializer._check_install private key is empty ')
         return False
     try:
         key.InitMyKey()
     except:
         if _Debug:
             lg.out(_DebugLevel, 'initializer._check_install fail loading private key ')
         return False
     try:
         ident = identity.identity(xmlsrc=current_id)
     except:
         if _Debug:
             lg.out(_DebugLevel, 'initializer._check_install fail init local identity ')
         return False
     if not ident.isCorrect():
         lg.err('local identity is not correct !!!')
         return False
     try:
         res = ident.Valid()
     except:
         if _Debug:
             lg.out(_DebugLevel, 'failed to validate local identity')
         return False
     if not res:
         lg.err('local identity is not valid !!!')
         return False
     if _Debug:
         lg.out(_DebugLevel, 'initializer._check_install SUCCESS!!!')
     return True
Beispiel #2
0
 def _check_install(self):
     """
     Return True if Private Key and local identity files exists and both is
     valid.
     """
     lg.out(2, 'initializer._check_install')
     from userid import identity
     from crypt import key
     keyfilename = settings.KeyFileName()
     keyfilenamelocation = settings.KeyFileNameLocation()
     if os.path.exists(keyfilenamelocation):
         keyfilename = bpio.ReadTextFile(keyfilenamelocation)
         if not os.path.exists(keyfilename):
             keyfilename = settings.KeyFileName()
     idfilename = settings.LocalIdentityFilename()
     if not os.path.exists(keyfilename) or not os.path.exists(idfilename):
         lg.out(
             2,
             'initializer._check_install local key or local id not exists')
         return False
     current_key = bpio.ReadBinaryFile(keyfilename)
     current_id = bpio.ReadBinaryFile(idfilename)
     if current_id == '':
         lg.out(2, 'initializer._check_install local identity is empty ')
         return False
     if current_key == '':
         lg.out(2, 'initializer._check_install private key is empty ')
         return False
     try:
         key.InitMyKey()
     except:
         lg.out(2, 'initializer._check_install fail loading private key ')
         return False
     try:
         ident = identity.identity(xmlsrc=current_id)
     except:
         lg.out(2, 'initializer._check_install fail init local identity ')
         return False
     try:
         res = ident.Valid() and ident.isCorrect()
     except:
         lg.out(
             2,
             'initializer._check_install wrong data in local identity   ')
         return False
     if not res:
         lg.out(2,
                'initializer._check_install local identity is not valid ')
         return False
     lg.out(2, 'initializer._check_install done')
     return True
Beispiel #3
0
def ForgetMyKey(keyfilename=None, erase_file=False, do_backup=False):
    """
    Remove Private Key from memory.
    """
    global _MyKeyObject
    if _MyKeyObject:
        _MyKeyObject.forget()
    _MyKeyObject = None
    if erase_file:
        if keyfilename is None:
            keyfilename = settings.KeyFileName()
        if do_backup:
            if os.path.isfile(keyfilename):
                current_pk_src = local_fs.ReadBinaryFile(keyfilename)
                if current_pk_src:
                    fd, fname = tempfile.mkstemp(prefix='mykeyfile_',
                                                 dir=settings.MetaDataDir())
                    os.write(fd, current_pk_src)
                    os.close(fd)
                    lg.info(
                        'created backup copy of my private key in the file : %r'
                        % fname)
        if os.path.isfile(keyfilename):
            os.remove(keyfilename)
            lg.info('local private key erased, deleted file : %r' %
                    keyfilename)
Beispiel #4
0
def isMyKeyExists(keyfilename=None):
    if keyfilename is None:
        keyfilename = settings.KeyFileName()
    if os.path.exists(keyfilename + '_location'):
        newkeyfilename = bpio.ReadTextFile(keyfilename + '_location').strip()
        if os.path.exists(newkeyfilename):
            keyfilename = newkeyfilename
    return os.path.exists(keyfilename)
Beispiel #5
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')
Beispiel #6
0
def GenerateNewKey(keyfilename=None):
    global _MyKeyObject
    global _MyRsaKey
    if keyfilename is None:
        keyfilename = settings.KeyFileName()
    if os.path.exists(keyfilename + '_location'):
        newkeyfilename = bpio.ReadTextFile(keyfilename + '_location').strip()
        if os.path.exists(newkeyfilename):
            keyfilename = newkeyfilename
    lg.out(4, 'key.InitMyKey generate new private key')
    _MyRsaKey = RSA.generate(settings.getPrivateKeySize(), os.urandom)
    _MyKeyObject = keys.Key(_MyRsaKey)
    keystring = _MyKeyObject.toString('openssh')
    bpio.WriteFile(keyfilename, keystring)
    lg.out(4, '    wrote %d bytes to %s' % (len(keystring), keyfilename))
Beispiel #7
0
def LoadMyKey(keyfilename=None):
    global _MyRsaKey
    global _MyKeyObject
    if keyfilename is None:
        keyfilename = settings.KeyFileName()
    if os.path.exists(keyfilename + '_location'):
        newkeyfilename = bpio.ReadTextFile(keyfilename + '_location').strip()
        if os.path.exists(newkeyfilename):
            keyfilename = newkeyfilename
    if os.path.exists(keyfilename):
        _MyKeyObject = keys.Key.fromFile(keyfilename)
        _MyRsaKey = _MyKeyObject.keyObject
        lg.out(4, 'key.InitMyKey loaded private key from %s' % (keyfilename))
        return ValidateKey()
    return False
Beispiel #8
0
def LoadMyKey(keyfilename=None):
    global _MyKeyObject
    if keyfilename is None:
        keyfilename = settings.KeyFileName()
    if os.path.exists(keyfilename + '_location'):
        newkeyfilename = bpio.ReadTextFile(keyfilename + '_location').strip()
        if os.path.exists(newkeyfilename):
            keyfilename = newkeyfilename
    if os.path.exists(keyfilename):
        _MyKeyObject = rsa_key.RSAKey()
        _MyKeyObject.fromFile(keyfilename)
        if _Debug:
            lg.out(_DebugLevel,
                   'key.InitMyKey loaded private key from %s' % (keyfilename))
        return ValidateKey()
    return False
Beispiel #9
0
def GenerateNewKey(keyfilename=None):
    global _MyKeyObject
    if keyfilename is None:
        keyfilename = settings.KeyFileName()
    if os.path.exists(keyfilename + '_location'):
        newkeyfilename = bpio.ReadTextFile(keyfilename + '_location').strip()
        if os.path.exists(newkeyfilename):
            keyfilename = newkeyfilename
    if _Debug:
        lg.out(_DebugLevel, 'key.InitMyKey generate new private key')
    _MyKeyObject = rsa_key.RSAKey()
    _MyKeyObject.generate(settings.getPrivateKeySize())
    keystring = _MyKeyObject.toPrivateString()
    bpio.WriteTextFile(keyfilename, keystring)
    if _Debug:
        lg.out(_DebugLevel, '    wrote %d bytes to %s' % (len(keystring), keyfilename))
    del keystring
    gc.collect()
Beispiel #10
0
 def setUp(self):
     from logs import lg
     from main import settings
     from crypt import key
     from userid import my_id
     lg.set_debug_level(30)
     settings.init()
     self.my_current_key = None
     if key.isMyKeyExists():
         os.rename(settings.KeyFileName(), '/tmp/_current_priv_key')
     fout = open('/tmp/_some_priv_key', 'w')
     fout.write(_some_priv_key)
     fout.close()
     if my_id.isLocalIdentityExists():
         os.rename(settings.LocalIdentityFilename(),
                   '/tmp/_current_localidentity')
     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())
Beispiel #11
0
def init(UI='', options=None, args=None, overDict=None, executablePath=None):
    """
    In the method ``main()`` program firstly checks the command line arguments
    and then calls this method to start the whole process.

    This initialize some low level modules and finally create an
    instance of ``initializer()`` state machine and send it an event
    "run".
    """
    global AppDataDir

    from logs import lg
    lg.out(4, 'bpmain.run UI="%s"' % UI)

    from system import bpio

    #---settings---
    from main import settings
    if overDict:
        settings.override_dict(overDict)
    settings.init(AppDataDir)
    if not options or options.debug is None:
        lg.set_debug_level(settings.getDebugLevel())
    from main import config
    config.conf().addCallback('logs/debug-level',
                              lambda p, value, o, r: lg.set_debug_level(value))

    #---USE_TRAY_ICON---
    if os.path.isfile(settings.LocalIdentityFilename()) and os.path.isfile(settings.KeyFileName()):
        try:
            from system.tray_icon import USE_TRAY_ICON
            if bpio.Mac() or not bpio.isGUIpossible():
                lg.out(4, '    GUI is not possible')
                USE_TRAY_ICON = False
            if USE_TRAY_ICON:
                from twisted.internet import wxreactor
                wxreactor.install()
                lg.out(4, '    wxreactor installed')
        except:
            USE_TRAY_ICON = False
            lg.exc()
    else:
        lg.out(4, '    local identity or key file is not ready')
        USE_TRAY_ICON = False
    lg.out(4, '    USE_TRAY_ICON=' + str(USE_TRAY_ICON))
    if USE_TRAY_ICON:
        from system import tray_icon
        icons_path = bpio.portablePath(os.path.join(bpio.getExecutableDir(), 'icons'))
        lg.out(4, 'bpmain.run call tray_icon.init(%s)' % icons_path)
        tray_icon.init(icons_path)

        def _tray_control_func(cmd):
            if cmd == 'exit':
                from . import shutdowner
                shutdowner.A('stop', 'exit')
        tray_icon.SetControlFunc(_tray_control_func)

    #---OS Windows init---
    if bpio.Windows():
        try:
            from win32event import CreateMutex  # @UnresolvedImport
            mutex = CreateMutex(None, False, "BitDust")
            lg.out(4, 'bpmain.run created a Mutex: %s' % str(mutex))
        except:
            lg.exc()

    #---twisted reactor---
    lg.out(4, 'bpmain.run want to import twisted.internet.reactor')
    try:
        from twisted.internet import reactor  # @UnresolvedImport
    except:
        lg.exc()
        sys.exit('Error initializing reactor in bpmain.py\n')

    #---logfile----
    if lg.logs_enabled() and lg.log_file():
        lg.out(2, 'bpmain.run want to switch log files')
        if bpio.Windows() and bpio.isFrozen():
            lg.stdout_stop_redirecting()
        lg.close_log_file()
        lg.open_log_file(settings.MainLogFilename())
        # lg.open_log_file(settings.MainLogFilename() + '-' + time.strftime('%y%m%d%H%M%S') + '.log')
        if bpio.Windows() and bpio.isFrozen():
            lg.stdout_start_redirecting()

    #---memdebug---
#    if settings.uconfig('logs.memdebug-enable') == 'True':
#        try:
#            from logs import memdebug
#            memdebug_port = int(settings.uconfig('logs.memdebug-port'))
#            memdebug.start(memdebug_port)
#            reactor.addSystemEventTrigger('before', 'shutdown', memdebug.stop)
#            lg.out(2, 'bpmain.run memdebug web server started on port %d' % memdebug_port)
#        except:
#            lg.exc()

    #---process ID---
    try:
        pid = os.getpid()
        pid_file_path = os.path.join(settings.MetaDataDir(), 'processid')
        bpio.WriteTextFile(pid_file_path, str(pid))
        lg.out(2, 'bpmain.run wrote process id [%s] in the file %s' % (str(pid), pid_file_path))
    except:
        lg.exc()

#    #---reactor.callLater patch---
#    if lg.is_debug(12):
#        patchReactorCallLater(reactor)
#        monitorDelayedCalls(reactor)

#    #---plugins---
#    from plugins import plug
#    plug.init()
#    reactor.addSystemEventTrigger('before', 'shutdown', plug.shutdown)

    lg.out(2, "    python executable is: %s" % sys.executable)
    lg.out(2, "    python version is:\n%s" % sys.version)
    lg.out(2, "    python sys.path is:\n                %s" % ('\n                '.join(sys.path)))

    lg.out(2, "bpmain.run UI=[%s]" % UI)

    if lg.is_debug(20):
        lg.out(0, '\n' + bpio.osinfofull())

    lg.out(4, 'import automats')

    #---START!---
    from automats import automat
    automat.LifeBegins(lg.when_life_begins())
    automat.OpenLogFile(settings.AutomatsLog())

    from main import events
    events.init()

    from main import initializer
    IA = initializer.A()
    lg.out(4, 'sending event "run" to initializer()')
    reactor.callWhenRunning(IA.automat, 'run', UI)  # @UndefinedVariable
    return IA
Beispiel #12
0
    def doVerifyAndRestore(self, arg):
        global _WorkingKey
        lg.out(4, 'identity_restorer.doVerifyAndRestore')

        remote_identity_src = arg

        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'))
            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'))
            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'))
            return

        key.ForgetMyKey()
        bpio.WriteFile(settings.KeyFileName(), _WorkingKey)
        try:
            key.InitMyKey()
        except:
            key.ForgetMyKey()
            # lg.exc()
            try:
                os.remove(settings.KeyFileName())
            except:
                pass
            reactor.callLater(0.1, self.automat, 'restore-failed',
                              ('private key is not valid', 'red'))
            return

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

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

        my_id.setLocalIdentity(local_ident)
        my_id.saveLocalIdentity()

        bpio.WriteFile(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')