Beispiel #1
0
 def getBackupAddMap(self):
     """"""
     data = None
     if Io.file_exists(self.addmapPath + Kirmah.EXT):
         call = " ".join(
             [
                 Sys.executable,
                 "kirmah-cli.py",
                 "dec",
                 "-qf",
                 self.addmapPath + Kirmah.EXT,
                 "-z",
                 "-r",
                 "-m",
                 "-o",
                 self.addmapPath,
                 "-k",
                 self.idxu.index.keyPath,
             ]
         )
         print(call)
         Sys.sysCall(call)
         data = jloads(Io.get_data(self.addmapPath))
         Io.removeFile(self.addmapPath)
     return data
Beispiel #2
0
    def onCommandDec(self):
        """"""
        done  = True
        if self.o.outputfile is None :
            self.o.outputfile = self.a[1][:-4] if self.a[1][-4:] == Kirmah.EXT else self.a[1]

        if not Sys.g.QUIET : self.parser.print_header()

        if Io.file_exists(self.o.outputfile) and not self.o.force:
            Sys.pwarn((('the file ',(self.o.outputfile, Sys.Clz.fgb3), ' already exists !'),))
            done  = Sys.pask('Are you sure to rewrite this file')
            self.stime = Sys.datetime.now()

        if done :

            try :

                if (self.o.multiprocess is not None and not represents_int(self.o.multiprocess)) or (not self.o.multiprocess is None and not(int(self.o.multiprocess)>=2 and int(self.o.multiprocess) <=8)) :
                    self.parser.error_cmd((('invalid option ',('-j, --multiprocess', Sys.Clz.fgb3), ' value (', ('2',Sys.Clz.fgb3),' to ', ('8',Sys.Clz.fgb3),')'),))

                nproc = int(self.o.multiprocess) if not self.o.multiprocess is None and int(self.o.multiprocess)>=2 and int(self.o.multiprocess) <=8 else 1

                Sys.ptask()

                key    = Io.get_data(self.o.keyfile)
                km     = Kirmah(key)

                km.decrypt(self.a[1], self.o.outputfile, nproc)

            except BadKeyException:
                done = False
                Sys.pwarn((('BadKeyException : ',('wrong key ',Sys.CLZ_WARN_PARAM), ' !'),), False)

        if not Sys.g.QUIET :
            self.onend_cmd('Kirmah Decrypt', self.stime, done, self.o.outputfile)
Beispiel #3
0
 def save(self,path=None,notAssign=False):
     """"""
     path = path if path is not None else self.path
     Io.set_data(path, '# last updated : '+str(Sys.datetime.now())+Const.LF+self.toString())
     call = ' '.join(['python3', 'kirmah-cli.py', 'enc', '-qf', path, '-z', '-r', '-m', '-o', path+'.kmh', '-k', self.keyPath ])
     Sys.sysCall(call)
     Io.removeFile(path)
     if not notAssign : self.path = path
Beispiel #4
0
 def createDefaultKeyIfNone(self):
     """"""
     kpath = self.getDefaultKeyPath()
     if not Io.file_exists(kpath):
         if Sys.isUnix():
             if not Sys.isdir(conf.DEFVAL_UKEY_PATH):
                 Sys.mkdir_p(conf.DEFVAL_UKEY_PATH)
                 Io.set_data(kpath, KeyGen(conf.DEFVAL_UKEY_LENGHT).key)
     self.selectKey(kpath)
Beispiel #5
0
 def _saveLocalIndex(self):
     """"""
     if not self.idx : self._getId()
     if self.idx :
         msg     = self.ih.getEmail(self.idx, True)
         content = b''
         for part in msg.walk():
             content += part.get_payload(decode=True)
         Io.set_data(self.pathIdx, a2b_base64(content), True)
Beispiel #6
0
 def buildIndex(self, fromPath):
     """Build mail for ImpraIndex
     :Returns: 'email.message.Message'
     """
     msg = MIMEText(Io.str(b2a_base64(Io.get_data(fromPath, True))), 'plain', 'utf-8')
     msg['From']    = self.getHashName('system')+'@'+self.DOMAIN_NAME
     msg['To']      = self.getHashName('all')+'@'+self.DOMAIN_NAME
     msg['Date']    = formatdate(localtime=True)
     msg['Subject'] = Header(self.getHashName('index'),'utf-8')      
     return msg
Beispiel #7
0
 def getKeyInfos(self, filename=None):
     """"""
     if filename is None:
         filename = self.getDefaultKeyPath()
     if not Io.file_exists(filename):
         raise FileNotFoundException(filename)
     k = Io.get_data(filename)
     s = len(k)
     m = KeyGen(s).getMark(k)
     return k, s, m
Beispiel #8
0
 def encrypt(self, fromPath=None):
     """"""
     if fromPath is None :
         fromPath = self.pathPlain
     Sys.pwlog([(' Encrypt Index... ' , Const.CLZ_0, True)])
     Io.set_data(fromPath, jdumps(self.dic))        
     call = ' '.join([Sys.executable, 'kirmah-cli.py', 'enc', '-qfj2' if Sys.isUnix() else '-qf', fromPath, '-z', '-r', '-m', '-o', fromPath+Kirmah.EXT, '-k', self.keyPath ])
     #~ print(call)
     Sys.sysCall(call)
     Io.removeFile(fromPath)
     Sys.pwlog([(' done', Const.CLZ_2, True)])   
     return Io.get_data(fromPath+Kirmah.EXT, True)
Beispiel #9
0
 def _getIdsList(ids):
     idslist = None
     if isinstance(ids,list):
         if len(ids) > 0 and ids[0]!='' and ids[0]!=None:
             li = len(ids)-1
             if int(ids[0])+li == int(ids[li]):
                 idslist = Io.str(ids[0]+b':'+ids[li]) if isinstance(ids[0],bytes) else str(ids[0])+':'+str(ids[li])
             else :
                 idslist = Io.str(b','.join(ids)) if isinstance(ids[0],bytes) else ','.join(ids)
     elif isinstance(ids, int) and ids > 0:
         idslist = Io.str(ids)
     return idslist
Beispiel #10
0
 def createDefaultKeyIfNone(self):
     """"""
     kpath = self.getDefaultKeyPath()
     if not Io.file_exists(kpath):
         #if Sys.isUnix() :
             if not Sys.isdir(conf.DEFVAL_UKEY_PATH) :
                 Sys.mkdir_p(conf.DEFVAL_UKEY_PATH)
             k = KeyGen(conf.DEFVAL_UKEY_LENGHT)
             print(k)
             content = k.key
             print('content')
             Io.set_data(kpath, content)
             print('set content')
     self.selectKey(kpath)
Beispiel #11
0
 def __init__(self, path, keyPath=None):
     """"""
     self.path    = path
     self.dic     = {}
     self.keyPath = path+'.key' if keyPath is None else keyPath
     if not Io.file_exists(self.keyPath) :
         kg = KeyGen()
         Io.set_data(self.keyPath, kg.key)            
         if not Io.file_exists(path) :                
             self.set('profile'  , 'default', 'main')
             self.set('key'  ,kg.key,'default.keys')
             self.set('mark' ,kg.mark,'default.keys')
             self.set('salt' ,'-*-ImpraStorage-*-','default.keys')
             self.save()
     self.read()
Beispiel #12
0
    def update(self):
        """"""
        self.switchFileAccount(self.conf.profile)
        try:
            if self.idx != None :
                if not isinstance(self.idx,bytes):
                    self.idx = Io.bytes(self.idx)                
                self.delids.append(self.idx)
        except Exception as e :
            Sys.dprint('error : ')
            Sys.dprint(e)   

        self.index.fixDuplicateIds()
        #~ self.index.fixAccount('gmail5')
        self.index.encrypt()
        msgIndex    = self.mb.buildIndex(self.pathIdx)
        _, self.idx = self.ih.send(msgIndex.as_string(), self.rootBox)
        date        = self.ih.headerField(self.idx, 'date', True)
        self.conf.sets((['uid'  , self.idx              , 'index'],
                       ['date' , date                   , 'index'],
                       ['time' , str(Sys.datetime.now()), 'index']))
        
        Sys.pwlog([(' Index updated ('  , Const.CLZ_0),
                   (str(int(self.idx))  , Const.CLZ_2),
                   (') '                , Const.CLZ_0),
                   (str(date)           , Const.CLZ_7, True)])
        
        try :
            self.ih.delete(self.delids, True)       
        except :
            Sys.dprint('error : ')
            Sys.dprint(e)
        self.ih.clearTrash()
        return True
Beispiel #13
0
    def on_proceed(self, btn):
        """"""
        if btn.get_label() == conf.GUI_LABEL_OK :
            btn.set_label(conf.GUI_LABEL_PROCEED)
            self.PROCEED = False
            self.pb.hide()
            self.show_log()

        else :
            if not self.PROCEED :
                self.PROCEED = True
                self.STOPPED = False
                btn.set_sensitive(False)
                self.app.setDestFile(self.get('filechooserbutton3').get_filename())
                if not Io.file_exists(self.app.dst) or self.warnDialog('file '+self.app.dst+' already exists', 'Overwrite file ?'):
                    self.pb = self.get('progressbar1')
                    self.pb.set_fraction(0)
                    self.pb.show()
                    self.pb.pulse()
                    btn.set_sensitive(True)
                    btn.set_label(conf.GUI_LABEL_CANCEL)
                    self.clear_log(self.get('checkbutton3'))
                    self.show_log()
                    self.launch_thread()
                else :
                    self.on_proceed_end(True)
            else :
                self.halt_thread()
Beispiel #14
0
 def selectKey(self, filename):
     """"""
     print('selectKey : ')
     print(filename)
     if not Io.file_exists(filename):
         raise FileNotFoundException(filename)
     self.kpath = filename
Beispiel #15
0
 def _ids(self, box='INBOX', search='ALL', charset=None, byUid=False):
     """"""
     status, resp = self.cnx.select(box)
     if status == self.KO :
         self.createBox(box)
         self.cnx.select(box)
     status, resp = self.cnx.search(charset, '(%s)' % search)
     return resplit(' ',Io.str(resp[self.K_HEAD]))
Beispiel #16
0
    def onCommandEnc(self):
        """"""
        done   = True
        if self.o.outputfile is None :
            self.o.outputfile = Sys.basename(self.a[1])
        if self.o.outputfile[-len(Kirmah.EXT):] != Kirmah.EXT :
            print(self.o.outputfile[-len(Kirmah.EXT):])
            self.o.outputfile += Kirmah.EXT
        print(self.o.outputfile)

        d        = self.getDefaultOption((self.o.compress,self.o.fullcompress,self.o.nocompress))
        compress = (KirmahHeader.COMP_END if d == 0 or (d is None and Io.is_binary(self.a[1])) else (KirmahHeader.COMP_ALL if d==1 or d is None else KirmahHeader.COMP_NONE))
        random   = True if (self.o.random is None and self.o.norandom is None) or self.o.random else False
        mix      = True if (self.o.mix is None and self.o.nomix is None) or self.o.mix else False

        if (self.o.multiprocess is not None and not represents_int(self.o.multiprocess)) or (not self.o.multiprocess is None and not(int(self.o.multiprocess)>=2 and int(self.o.multiprocess) <=8)) :
            self.parser.error_cmd((('invalid option ',('-j, --multiprocess', Sys.Clz.fgb3), ' value (', ('2',Sys.Clz.fgb3),' to ', ('8',Sys.Clz.fgb3),')'),))

        nproc = int(self.o.multiprocess) if not self.o.multiprocess is None and int(self.o.multiprocess)>=2 and int(self.o.multiprocess) <=8 else 1

        if not Sys.g.QUIET : self.parser.print_header()

        if Io.file_exists(self.o.outputfile) and not self.o.force:
            Sys.pwarn((('the file ',(self.o.outputfile, Sys.Clz.fgb3), ' already exists !'),))
            done  = Sys.pask('Are you sure to rewrite this file')
            self.stime = Sys.datetime.now()

        if done :

            try :
                Sys.ptask()

                key    = Io.get_data(self.o.keyfile)
                km     = Kirmah(key, None, compress, random, mix)

                km.encrypt(self.a[1], self.o.outputfile, nproc)

            except Exception as e :
                done = False
                print(e)
                raise e
                pass

        if not Sys.g.QUIET :
            self.onend_cmd('Kirmah Encrypt', self.stime, done, self.o.outputfile)
Beispiel #17
0
 def listBox(self, box='INBOX', pattern='*'):
     """"""
     status, resp = self.cnx.list(box,pattern)
     l = []
     for r in resp :
         if  r is not None :
             name = Io.str(r).split(' "/" ')
             l.append((name[0][1:-1].split(' '),name[1][1:-1]))
     return l
Beispiel #18
0
 def headerField(self, mid, field, byUid=False):
     """"""
     value = ''
     field = field.upper()
     query = '(UID BODY[HEADER' + ('])' if field=='*' or field=='ALL' else '.FIELDS (%s)])' % field)
     status, resp = self.fetch(mid, query, byUid)
     if status==self.OK and resp[0]!=None:
         value = Io.str(resp[0][1][len(field)+2:-4])
     return value
Beispiel #19
0
    def onCommandExport(self):
        """"""
        Sys.clear()
        self.pheader()
        from time import strftime

        name = strftime("%Y%m%d%H%M%S") + "_" + self.impst.idxu.conf.profile
        Sys.echo(" saving ", Sys.Clz.fgn7, False)
        Sys.echo(name + ".index" + Kirmah.EXT, Sys.Clz.fgB2)
        Io.copy(self.impst.idxu.pathIdx, name + ".index" + Kirmah.EXT)
        Sys.echo(" saving ", Sys.Clz.fgn7, False)
        Sys.echo(name + ".ini" + Kirmah.EXT, Sys.Clz.fgB2)
        self.impst.idxu.conf.ini.save(name + ".ini", True)
        Sys.echo(" saving ", Sys.Clz.fgn7, False)
        Sys.echo(name + ".key", Sys.Clz.fgB2)
        Io.set_data(name + ".key", self.impst.idxu.conf.get("key", "keys"))
        Sys.dprint("\n ", end="")
        Sys.echo(" == OK == ", Sys.Clz.bg2 + Sys.Clz.fgb7)
        Sys.dprint()
Beispiel #20
0
 def get(self, forceRefresh=False):
     """"""
     self.switchFileAccount(self.conf.profile)
     index   = None
     uid     = self.conf.get('uid'  ,'index')
     date    = self.conf.get('date' ,'index')
     tstamp  = self.conf.get('time' ,'index')
     refresh = forceRefresh        
     delta   = None if tstamp is None else Sys.datetime.now() - Sys.datetime.strptime(tstamp[:-7], '%Y-%m-%d %H:%M:%S')
     if not refresh and tstamp is not None and delta < Sys.timedelta(minutes = 3) :
         # getFromFile            
         if uid != None and Io.file_exists(self.pathIdx): # int(self.idx) == int(uid) 
             self.idx = uid
             Sys.pwlog([(' Get index from cache '  , Const.CLZ_7),
                        ('('                       , Const.CLZ_0),
                        (str(int(self.idx))        , Const.CLZ_2),
                        (')'                       , Const.CLZ_0, True)])
         else: refresh = True
     else: refresh = True
     self.irefresh = refresh
     if refresh :
         Sys.pwlog([(' Checking index...', Const.CLZ_0, True)])
         self._getId()
         if self.idx :
             if int(self.idx) != int(uid) or not Io.file_exists(self.pathIdx):
                 Sys.pwlog([(' Refreshing index (local:', Const.CLZ_0),
                            (str(int(uid))              , Const.CLZ_2),
                            (' / remote:'               , Const.CLZ_0),
                            (str(int(self.idx))         , Const.CLZ_1),
                            (')'                        , Const.CLZ_0, True)])
                 
                 date = self.ih.headerField(self.idx, 'date', True)
                 self.conf.sets((['uid'  , str(int(self.idx))     , 'index'],
                                 ['date' , date                   , 'index'],
                                 ['time' , str(Sys.datetime.now()), 'index']))
                 self._saveLocalIndex()
             else :
                 Sys.pwlog([(' Get index from cache '  , Const.CLZ_7),
                            ('('                       , Const.CLZ_0),
                            (str(int(self.idx))        , Const.CLZ_2),
                            (')'                       , Const.CLZ_0, True)])
             self.conf.set('time',str(Sys.datetime.now()),'index')
     self.build()        
Beispiel #21
0
 def read(self):
     """"""
     try:
         call = ' '.join([Sys.executable, 'kirmah-cli.py', 'dec', '-qf', self.path+'.kmh', '-z', '-r', '-m', '-o', self.path, '-k', self.keyPath ])
         Sys.sysCall(call)            
         with Io.rfile(self.path, False) as fi:
             csection = 'main'
             self.dic[csection] = {}
             for l in fi:
                 l = l.rstrip().lstrip()
                 if len(l) > 0 and not l[0]=='#' :
                     d = regsplit(' *= *', l , 1)
                     if len(d)> 1:
                         self.dic[csection][d[0]] = d[1] if d[1] is not None else ''
                     elif len(l)>0 and l[0]=='[':
                         csection = l.strip('[]')
                         self.dic[csection] = {}
         Io.removeFile(self.path)
     except IOError :
         pass
Beispiel #22
0
 def status(self, box='INBOX'):
     """"""
     status, resp = self.cnx.status(box, '(MESSAGES RECENT UIDNEXT UIDVALIDITY UNSEEN)')
     if status == self.OK :
         data = research(self.REG_SATUS, Io.str(resp[self.K_HEAD]))
         l    = resplit(' ',data.group(2))
         dic  = {'BOX' : box}
         for i in range(len(l)):
             if i%2 == 0 : dic[l[i]] = int(l[i+1])
     else : dic = {}
     return dic
Beispiel #23
0
 def decrypt(self, fromPath=None):
     """"""        
     done = False
     try :
         if fromPath is None :
             fromPath = self.path
         toPath = fromPath[:-len(Kirmah.EXT)] if fromPath.endswith(Kirmah.EXT) else fromPath+'.dump'
         if Io.file_exists(fromPath) :
             Sys.pwlog([(' Decrypt Index... '                        , Const.CLZ_0, True)])
             call = ' '.join([Sys.executable, 'kirmah-cli.py', 'dec', '-qfj2' if Sys.isUnix() else '-qf', fromPath, '-z', '-r', '-m', '-o', toPath, '-k', self.keyPath ])
             print(call)
             Sys.sysCall(call)
             data   = jloads(Io.get_data(toPath))
             Io.removeFile(toPath)
         else :
             data = {}
         done = True
     except ValueError as e:
         raise BadKeyException(e)
     Sys.pwlog([(' done'if done else ' ko'    , Const.CLZ_2 if done else Const.CLZ_1, True)])
     return data
Beispiel #24
0
    def __init__(self, home, path, parser, Cli, a, o):
        """"""
        self.parser = parser
        self.Cli = Cli
        self.a = a
        self.o = o
        self.home = home
        self.stime = Sys.datetime.now()
        self.account = "default"
        self.rootBox = "__impra__2"
        self.uid = "0"
        self.date = ""
        if not Io.file_exists("impra2.ini" + Kirmah.EXT):
            print("ini file not exist")
            if len(self.a) > 0 and self.a[0] == "conf" and self.o.save:
                kg = KeyGen()
                Io.set_data("impra2.ini.key", kg.key)
                self.ini = KiniFile("impra2.ini")
                self.ini.set("key", kg.key, self.account + ".keys")
                self.ini.set("mark", kg.mark, self.account + ".keys")
                self.ini.set("salt", "-¤-ImpraStorage-¤-", self.account + ".keys")
            else:
                self.needConfig()

        else:
            if not (len(self.a) > 0 and self.a[0] == "conf"):
                self.ini = KiniFile("impra2.ini")
                self.impst = ImpraStorage(ImpraConf(self.ini), wkdir=path)
                self.uid = self.impst.idxu.conf.get("uid", "index")
                self.date = self.impst.idxu.conf.get("date", "index")
                self.account = self.impst.idxu.conf.get("user", "imap")
                self.rootBox = self.impst.rootBox
                if self.impst.idxu.index != None:
                    noData = self.impst.idxu.index.isEmpty()
                    if self.uid == None or noData:
                        self.uid = "EMPTY"
                    if self.date == None or noData:
                        self.date = ""
            else:
                self.ini = KiniFile("impra2.ini")
Beispiel #25
0
 def getAttachment(self, msg, toDir='./', byUid=False):
     """"""
     # self.download(msg, toDir, byUid, False)
     # p = Process(target=self.download, args=(msg, toDir, byUid))
     # p.start()
     # p.join()
     if not isinstance(msg, Message) :
         msg = self.getEmail(msg, byUid)
     for part in msg.walk():
         filename = part.get_filename()
         if part.get_content_maintype() == 'multipart' or not filename : continue
         with Io.wfile(Sys.join(toDir, filename)) as fo :
             fo.write(part.get_payload(decode=True))
Beispiel #26
0
 def backupAddMap(self, data):
     """"""
     Io.set_data(self.addmapPath, jdumps(data))
     call = " ".join(
         [
             Sys.executable,
             "kirmah-cli.py",
             "enc",
             "-qf",
             self.addmapPath,
             "-z",
             "-r",
             "-m",
             "-o",
             self.addmapPath + Kirmah.EXT,
             "-k",
             self.idxu.index.keyPath,
         ]
     )
     print(call)
     Sys.sysCall(call)
     Io.removeFile(self.addmapPath)
Beispiel #27
0
 def remove(self):
     """"""
     self._getId()
     try:
         if self.idx!= None : self.delids.append(Io.bytes(self.idx))
         self.ih.delete(self.delids, True)
         self.idx = None
     except Exception as e :
         Sys.dprint('error : ')
         Sys.dprint(e)
         
     self.ih.clearTrash()
     self.removeLocal()
Beispiel #28
0
 def initBoxNames(self):
     """"""
     status, resp = self.cnx.xlist()
     if status == self.OK :
         bdef, bname, c = None, None, None
         for c in resp :
             bdef, bname = c[1:-1].split(b') "/" "')
             if bdef == Io.bytes(self.NO_SELECT+' '+self.CHILDREN) :
                 self.BOXS['/'] = Io.str(bname)
             elif bdef == Io.bytes(self.NO_CHILDREN+' '+self.INBOX) :
                 self.BOXS[self.INBOX] = self.INBOX[1:].upper()
             elif bdef == Io.bytes(self.NO_CHILDREN+' '+self.DRAFTS) :
                 self.BOXS[self.DRAFTS] = Io.str(bname)
             elif bdef == Io.bytes(self.NO_CHILDREN+' '+self.TRASH) :
                 self.BOXS[self.TRASH] = Io.str(bname)
             elif bdef == Io.bytes(self.NO_CHILDREN+' '+self.SENT) :
                 self.BOXS[self.SENT] = Io.str(bname)
     else :
         self.BOXS = { '/' : '/', self.INBOX : self.INBOX[1:].upper(), self.DRAFTS : self.DRAFTS[1:], self.TRASH : self.TRASH[1:], self.SENT : self.SENT[1:] }
Beispiel #29
0
    def __init__(self, key, path, dicCategory={}, accountList={}, emit=False):
        """Initialize the index with rsa and encoded data

        :Parameters:
            `key`     : str
                appropriate key to decrypt/encrypt data
            `mark`    : str
                appropriate mark to check correct key
            `encdata` : str
                initial content of the index encrypted with Kirmah Algorythm
                and representing a dic index as json string
        """
        self.pathPlain = path[:-len(Kirmah.EXT)]
        self.keyPath   = self.pathPlain+self.KEY_EXT
        self.path      = path
        Io.set_data(self.keyPath, key)
        self.dic       = {}
        self.acclist   = accountList
        encdata        = Io.get_data(path, True) if Io.file_exists(path) else b''

        if encdata == b'' :
            self.dic = {}
            self.id  = 1
        else :
            self.dic = self.decrypt(path)
            l        = [self.dic[k][self.UID] for i, k in enumerate(self.dic) if not k.startswith(self.SEP_KEY_INTERN)]
            if len(l) > 0 :
                self.id = max(l)+1
            else: self.id = 1
        for k in dicCategory :
            if k == 'users' :
                for k1 in dicCategory[k]:
                    if self.SEP_KEY_INTERN+k in self.dic:
                        if k1 not in self.dic[self.SEP_KEY_INTERN+k]:
                            self.dic[self.SEP_KEY_INTERN+k][k1] = dicCategory[k][k1]
            else :
                if not self.SEP_KEY_INTERN+k in self.dic:
                    self.dic[self.SEP_KEY_INTERN+k] = dicCategory[k]
Beispiel #30
0
    def onCommandKey(self):
        """"""
        if int(self.o.length) >= 128 and int(self.o.length) <= 4096 :
            self.parser.print_header()
            if not self.o.outputfile : self.o.outputfile = self.home+'.kirmah'+Sys.sep+'.default.key'
            kg   = KeyGen(int(self.o.length))
            done = True
            if Io.file_exists(self.o.outputfile) and not self.o.force :

                Sys.pwarn((('the key file ',(self.o.outputfile, Sys.Clz.fgb3), ' already exists !'),
                           'if you rewrite this file, all previous files encrypted with the corresponding key will be unrecoverable !'))

                done   = Sys.pask('Are you sure to rewrite this file')
                self.stime  = Sys.datetime.now()
            if done :
                Io.set_data(self.o.outputfile, kg.key)
            Sys.pstep('Generate key file', self.stime, done)

            if done :
                Sys.print(' '*5+Sys.realpath(self.o.outputfile), Sys.Clz.fgB1, True)

        else :
            self.parser.error_cmd((('invalid option ',('-l, --length', Sys.Clz.fgb3), ' value (', ('128',Sys.Clz.fgb3),' to ', ('4096',Sys.Clz.fgb3),')'),))
Beispiel #31
0
    def __init__(self,
                 path,
                 remote=False,
                 rwargs=None,
                 thread=None,
                 loglvl=Const.LOG_DEFAULT):
        """"""
        AbstractCli.__init__(self, conf, self)

        Cli.HOME = conf.DEFVAL_USER_PATH
        Cli.DIRKEY = Cli.HOME + '.' + conf.PRG_NAME.lower() + Sys.sep
        if not Sys.isUnix():
            CHQ = '"'
            self.HOME = 'C:' + Sys.sep + conf.PRG_NAME.lower() + Sys.sep
            self.DIRKEY = self.HOME + 'keys' + Sys.sep
        Sys.mkdir_p(Cli.DIRKEY)

        gpData = OptionGroup(self.parser, '')
        gpData.add_option('-a', '--fullcompress', action='store_true')
        gpData.add_option('-z', '--compress', action='store_true')
        gpData.add_option('-Z', '--nocompress', action='store_true')
        gpData.add_option('-r', '--random', action='store_true')
        gpData.add_option('-R', '--norandom', action='store_true')
        gpData.add_option('-m', '--mix', action='store_true')
        gpData.add_option('-M', '--nomix', action='store_true')
        gpData.add_option('-j', '--multiprocess', action='store')
        gpData.add_option('-k', '--keyfile', action='store')
        gpData.add_option('-l', '--length', action='store', default=1024)
        gpData.add_option('-p', '--parts', action='store', default=22)
        gpData.add_option('-o', '--outputfile', action='store')
        self.parser.add_option_group(gpData)

        # rewrite argv sended by remote
        if rwargs is not None:
            import sys
            sys.argv = rwargs

        (o, a) = self.parser.parse_args()

        Sys.g.QUIET = o.quiet
        Sys.g.THREAD_CLI = thread
        Sys.g.GUI = thread is not None

        init(conf.PRG_NAME, o.debug, remote, not o.no_color, loglvl)

        if not a:
            try:
                if not o.help or not o.version:
                    self.parser.error_cmd(('no command specified', ), True)
                else:
                    Sys.clear()
                    Cli.print_help()
            except:
                if not o.version:
                    self.parser.error_cmd(('no command specified', ), True)
                else:
                    Cli.print_header()

        else:
            if a[0] == 'help':
                Sys.clear()
                Cli.print_help()

            elif a[0] in ['key', 'enc', 'dec', 'split', 'merge']:

                app = CliApp(self.HOME, path, self, a, o)

                if a[0] == 'key':
                    app.onCommandKey()
                else:
                    if not len(a) > 1:
                        self.parser.error_cmd(
                            (('an ', ('inputFile', Sys.Clz.fgb3),
                              ' is required !'), ), True)
                    elif not Io.file_exists(a[1]):
                        self.parser.error_cmd(
                            (('the file ',
                              (a[1], Sys.Clz.fgb3), ' doesn\'t exists !'), ),
                            True)

                    elif a[0] == 'enc':
                        app.onCommandEnc()
                    elif a[0] == 'dec':
                        app.onCommandDec()
                    elif a[0] == 'split':
                        app.onCommandSplit()
                    elif a[0] == 'merge':
                        app.onCommandMerge()

                    Sys.dprint('PUT END SIGNAL')
                    if Sys.g.LOG_QUEUE is not None:
                        Sys.g.LOG_QUEUE.put(Sys.g.SIGNAL_STOP)

            else:
                self.parser.error_cmd(
                    (('unknow command ', (a[0], Sys.Clz.fgb3)), ))

        if not o.quiet: Sys.dprint()
Beispiel #32
0
 def selectKey(self, filename):
     """"""
     if not Io.file_exists(filename):
         raise FileNotFoundException(filename)
     self.kpath = filename
Beispiel #33
0
 def setSourceFile(self, filename):
     """"""
     if not Io.file_exists(filename) :
         raise FileNotFoundException()
     else :
         self.src = filename
Beispiel #34
0
    def onCommandEnc(self):
        """"""
        done = True
        if self.o.outputfile is None:
            self.o.outputfile = Sys.basename(self.a[1])
        if self.o.outputfile[-len(Kirmah.EXT):] != Kirmah.EXT:
            print(self.o.outputfile[-len(Kirmah.EXT):])
            self.o.outputfile += Kirmah.EXT
        print(self.o.outputfile)

        d = self.getDefaultOption(
            (self.o.compress, self.o.fullcompress, self.o.nocompress))
        compress = (KirmahHeader.COMP_END if d == 0 or
                    (d is None and Io.is_binary(self.a[1])) else
                    (KirmahHeader.COMP_ALL
                     if d == 1 or d is None else KirmahHeader.COMP_NONE))
        random = True if (self.o.random is None and
                          self.o.norandom is None) or self.o.random else False
        mix = True if (self.o.mix is None
                       and self.o.nomix is None) or self.o.mix else False

        if (self.o.multiprocess is not None
                and not represents_int(self.o.multiprocess)) or (
                    not self.o.multiprocess is None
                    and not (int(self.o.multiprocess) >= 2
                             and int(self.o.multiprocess) <= 8)):
            self.parser.error_cmd(
                (('invalid option ', ('-j, --multiprocess',
                                      Sys.Clz.fgb3), ' value (',
                  ('2', Sys.Clz.fgb3), ' to ', ('8', Sys.Clz.fgb3), ')'), ))

        nproc = int(
            self.o.multiprocess) if not self.o.multiprocess is None and int(
                self.o.multiprocess) >= 2 and int(
                    self.o.multiprocess) <= 8 else 1

        if not Sys.g.QUIET: self.parser.print_header()

        if Io.file_exists(self.o.outputfile) and not self.o.force:
            Sys.pwarn((('the file ', (self.o.outputfile, Sys.Clz.fgb3),
                        ' already exists !'), ))
            done = Sys.pask('Are you sure to rewrite this file')
            self.stime = Sys.datetime.now()

        if done:

            try:
                Sys.ptask()

                key = Io.get_data(self.o.keyfile)
                km = Kirmah(key, None, compress, random, mix)

                km.encrypt(self.a[1], self.o.outputfile, nproc)

            except Exception as e:
                done = False
                print(e)
                raise e
                pass

        if not Sys.g.QUIET:
            self.onend_cmd('Kirmah Encrypt', self.stime, done,
                           self.o.outputfile)
Beispiel #35
0
    def onCommandMerge(self):
        """"""
        done = True

        if not Sys.g.QUIET: self.parser.print_header()

        if done:
            toPath = None
            try:
                Sys.ptask()

                key = Io.get_data(self.o.keyfile)
                km = Kirmah(key)
                kcf = None
                istar = True
                try:
                    import tarfile
                    dpath = Sys.dirname(
                        Sys.realpath(self.o.outputfile)
                    ) + Sys.sep if self.o.outputfile is not None else Sys.dirname(
                        Sys.realpath(self.a[1])) + Sys.sep
                    if self.o.outputfile is None:
                        self.o.outputfile = dpath
                    with tarfile.open(self.a[1], mode='r') as tar:
                        #~ print(dpath)
                        tar.extractall(path=dpath)
                        kcf = None
                        for tarinfo in tar:
                            #~ print(tarinfo.name)
                            if tarinfo.isreg() and tarinfo.name[-4:] == '.kcf':
                                #~ print(dpath+tarinfo.name)
                                kcf = dpath + tarinfo.name
                    if kcf is not None:
                        km.DIR_OUTBOX = dpath
                        toPath = km.mergeFile(kcf, self.o.outputfile)
                except BadKeyException:
                    Sys.pwarn((('BadKeyException : ',
                                ('wrong key ', Sys.CLZ_WARN_PARAM), ' !'), ),
                              False)
                    done = False

                except Exception:
                    istar = False
                    toPath = km.mergeFile(self.a[1], self.o.outputfile)

                #~ if self.o.outputfile is not None :
                #~ Io.rename(toPath, self.o.outputfile)
                #~ toPath = self.o.outputfile

            except BadKeyException:
                Sys.pwarn((('BadKeyException : ',
                            ('wrong key ', Sys.CLZ_WARN_PARAM), ' !'), ),
                          False)
                done = False

            except Exception as e:
                done = False
                if Sys.g.DEBUG:
                    print(e)
                elif not Sys.g.QUIET:
                    Sys.pwarn((str(e), ))
        if not done:
            if istar:
                with tarfile.open(self.a[1], mode='r') as tar:
                    for tarinfo in tar:
                        Sys.removeFile(dpath + tarinfo.name)

        if not Sys.g.QUIET:
            self.onend_cmd('Kirmah Merge', self.stime, done, toPath)
Beispiel #36
0
    def onCommandSplit(self):
        """"""
        done = True
        Sys.cli_emit_progress(1)
        if not self.o.parts is None and not (int(self.o.parts) >= 12
                                             and int(self.o.parts) <= 62):
            self.parser.error_cmd(
                (('invalid option ', ('-p, --parts', Sys.Clz.fgb3), ' value (',
                  ('12', Sys.Clz.fgb3), ' to ', ('62', Sys.Clz.fgb3), ')'), ))
        else:
            self.o.parts = int(self.o.parts)

        if not Sys.g.QUIET: self.parser.print_header()
        if self.o.outputfile is not None:
            if self.o.outputfile[-5:] != '.tark': self.o.outputfile += '.tark'
            if Io.file_exists(self.o.outputfile) and not self.o.force:
                Sys.pwarn((('the file ', (self.o.outputfile, Sys.Clz.fgb3),
                            ' already exists !'), ))
                done = Sys.pask('Are you sure to rewrite this file')
                self.stime = Sys.datetime.now()

        if done:

            try:
                Sys.ptask()
                Sys.cli_emit_progress(2)
                key = Io.get_data(self.o.keyfile)
                km = Kirmah(key)
                hlst = km.ck.getHashList(Sys.basename(self.a[1]), self.o.parts,
                                         True)
                Sys.cli_emit_progress(3)
                kcf = km.splitFile(self.a[1], hlst)
                t = int(Sys.time())
                times = (t, t)
                p = 85
                Sys.cli_emit_progress(p)
                Io.touch(kcf, times)
                frav = 0.24
                for row in hlst['data']:
                    p += frav
                    Io.touch(row[1] + km.EXT, times)
                    Sys.cli_emit_progress(p)
                if self.o.outputfile is not None:
                    d = Sys.datetime.now()
                    if Sys.g.DEBUG: Sys.wlog(Sys.dprint())
                    Sys.ptask('Preparing tark file')
                    hlst['data'] = sorted(hlst['data'], key=lambda lst: lst[4])
                    with tarfile.open(self.o.outputfile, mode='w') as tar:
                        tar.add(kcf, arcname=Sys.basename(kcf))
                        p = 90
                        for row in hlst['data']:
                            tar.add(row[1] + km.EXT,
                                    arcname=Sys.basename(row[1] + km.EXT))
                            p += frav
                            Sys.cli_emit_progress(p)
                    Sys.pstep('Packing destination file', d, True)
                    d = Sys.datetime.now()
                    Sys.ptask('Finalize')
                    for row in hlst['data']:
                        Io.removeFile(row[1] + km.EXT)
                        p += frav
                        Sys.cli_emit_progress(p)
                    Io.removeFile(kcf)
                    Sys.pstep('Cleaning', d, True)

            except Exception as e:
                done = False
                if Sys.g.DEBUG:
                    print('split exception')
                    print(e)

                    #~ raise e
                elif not Sys.g.QUIET:
                    Sys.pwarn((str(e), ))

        if not Sys.g.QUIET:
            Sys.cli_emit_progress(100)
            self.onend_cmd('Kirmah Split', self.stime, done, self.o.outputfile)
Beispiel #37
0
 def hasSrcFile(self):
     """"""
     return Io.file_exists(self.src)
Beispiel #38
0
 def createNewKey(self, filename, size):
     """"""
     if not Sys.isdir(Sys.dirname(filename)):
         Sys.mkdir_p(Sys.dirname(filename))
     Io.set_data(filename,KeyGen(size).key[:size])