def __init__(self, **arg): super(BaseSocket, self).__init__() self.msgCode = ('login', 'logout', 'refresh', 'list', 'get', 'put') self.userName = None self.passWord = None self.host = None self.port = None self.sslContext = None self.SEND_BUFFER_SIZE = 1024 self.ctrlSock = None self.ctrlSockPort = None self.dataSock = None self.dataSockPort = None self.recvInfo = None self.lastCmd = None self.lastCmdCode = None self.certInfo = None if arg: self.__dict__.update(arg) self.log = Syslog() self.settings = Settings()
def __init__(self, **arg): super(BaseSocket, self).__init__() # self.clientSocket = clientSocket # self.clientAddress = clientAddress self.log = Syslog() self.settings = Settings() self.SEND_CMD_BUFFER_SIZE = self.settings['DEFAULT'].getint( 'SEND_CMD_BUFFER_SIZE') self.SEND_FILE_BUFFER_SIZE = self.settings['DEFAULT'].getint( 'SEND_FILE_BUFFER_SIZE') self.RECV_CMD_BUFFER_SIZE = self.settings['DEFAULT'].getint( 'RECV_CMD_BUFFER_SIZE') self.__dict__.update(arg)
class Status(threading.Thread): """docstring for Status.""" def __init__(self): super(Status, self).__init__() self.log = Syslog() def run(self): while True: time.sleep(5) self.log.info("============================") self.log.info( "now have {} worker".format(threading.active_count() - 2)) self.log.info("============================")
def __init__(self): super(SSLCertSetting, self).__init__() self.log = Syslog() self.settings = Settings()
class SSLCertSetting(object): """docstring for SSLCertSetting.""" def __init__(self): super(SSLCertSetting, self).__init__() self.log = Syslog() self.settings = Settings() def create_self_signed_cert(self, common_name): C_F = self.settings.certificates.certificate K_F = self.settings.certificates.privatekey P_F = joinFilePath( getDirNameByPath(self.settings.certificates.privatekey), 'server.pub.key') if not exists(C_F) or not exists(K_F): k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 2048) cert = crypto.X509() cert.get_subject().C = self.settings.certificates.country cert.get_subject().ST = self.settings.certificates.state cert.get_subject().L = self.settings.certificates.city cert.get_subject().O = self.settings.certificates.organization cert.get_subject().OU = self.settings.certificates.unit cert.get_subject().CN = common_name cert.set_serial_number(1000) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(315360000) cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) cert.sign(k, 'sha1') with open(C_F, "wb") as f: f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) with open(K_F, "wb") as f: f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) with open(P_F, "wb") as f: f.write(crypto.dump_publickey(crypto.FILETYPE_PEM, k)) def validate_ssl_cert(self): certificate = getFileContent(self.settings.certificates.certificate) privatekey = getFileContent(self.settings.certificates.privatekey) certs = CERT_PATTERN.findall(certificate) if not certs: self.log.error( "SSL certificate is invalid: no certificate found {}".format( self.settings.certificates.certificate)) exit() priv_keys = PRIVATE_KEY_PATTERN.findall(privatekey) if not priv_keys: self.log.error( "SSL private key is invalid: no private key found {}".format( self.settings.certificates.privatekey)) exit() def _load_certificate(cert_data): try: return load_certificate(FILETYPE_PEM, cert_data) except Exception as e: self.log.error("validate ssl certs failed: {}.".format(e)) exit() def _load_private_key(private_key_data): try: return load_privatekey(FILETYPE_PEM, private_key_data) except Exception as e: self.log.error("validate ssl private key failed: {}".format(e)) exit() # check first part to ensure pem file is loadable crt = _load_certificate(certs[0]) key = _load_private_key(priv_keys[0]) crt_chain = [_load_certificate(c) for c in certs] key_chain = [_load_private_key(p) for p in priv_keys] try: ctx = OpenSSL.SSL.Context(OpenSSL.SSL.TLSv1_METHOD) ctx.use_privatekey(key) ctx.use_certificate(crt) ctx.check_privatekey() except Exception as e: self.log.error( "cert pem files key pair is not matched: {}.".format(e)) exit() crt_chain_data = b''.join( [dump_certificate(FILETYPE_PEM, cc) for cc in crt_chain]) key_chain_data = b''.join( [dump_privatekey(FILETYPE_PEM, kc) for kc in key_chain]) return crt_chain_data, key_chain_data
class BaseSocket(object): """docstring for Client.""" def __init__(self, **arg): super(BaseSocket, self).__init__() self.msgCode = ('login', 'logout', 'refresh', 'list', 'get', 'put') self.userName = None self.passWord = None self.host = None self.port = None self.sslContext = None self.SEND_BUFFER_SIZE = 1024 self.ctrlSock = None self.ctrlSockPort = None self.dataSock = None self.dataSockPort = None self.recvInfo = None self.lastCmd = None self.lastCmdCode = None self.certInfo = None if arg: self.__dict__.update(arg) self.log = Syslog() self.settings = Settings() def createConnection(self): ret = self.createSslConttext() self.log.info( 'createSslConttext return {} ,start createConnection'.format( str(ret))) try: tmpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.ctrlSock = self.sslContext.wrap_socket( tmpSock, server_hostname='0.0.0.0') self.ctrlSock.connect((self.host, int(self.port))) except Exception as e: self.log.info(str(e)) return (1, str(e)) else: self.certInfo = str(self.ctrlSock.cipher()) self.log.info('connecting to remote host ...') return (0, ) def createSslConttext(self): self.sslContext = ssl.create_default_context() certFileName = "{}.crt".format(self.host) certFilePath = utils.joinFilePath(self.settings.certificates.certdirs, certFileName) print('fuck1') if not utils.checkFileExists(certFilePath): # get remote certificates self.acquire_remote_cert() try: # verify_cert utils.verify_cert(certFilePath, self.host) except Exception as e: self.log.error(str(e)) return (1, str(e)) print('fuck2') try: self.sslContext.load_verify_locations(certFilePath) except Exception as e: self.log.error(str(e)) return (1, str(e)) def createDataSock(self): self.dataSock = self.ctrlSock def acquire_remote_cert(self): self.log.info('start acquire remote host cert') try: cert = ssl.get_server_certificate((self.host, self.port)) except Exception as e: self.log.info('can\' t load remote certificate :{}'.format(str(e))) return (1, str(e)) certFileName = "{}.crt".format(self.host) certFilePath = utils.joinFilePath(self.settings.certificates.certdirs, certFileName) try: with open(certFilePath, 'w') as f: f.write(cert) except Exception as e: self.log.info( 'can\' t save remote certificate on local :{}'.format(str(e))) return (1, str(e)) else: self.log.info('load and save remote server cert successd') return (0, 'ok') def sendFile(self): with open(self.filepath, 'rb') as f: try: sendSize = self.ctrlSock.sendfile(f) except Exception as e: self.log.info('send file fails : {}'.format(str(e))) else: self.log.info('send file Successd') finally: self.log.info('total send size is :{:.2f} M'.format(sendSize / 1024)) def recvFile(self): self.log.info('######## start recv file ########') self.log.info('######## size of file is : {}########'.format( self.fileSize)) loop = int(self.fileSize) // 1024 extend = int(self.fileSize) % 1024 with open(self.saveFilePath_E, 'wb') as f: recvedFileSize = 0 for i in range(loop): recvfile = self.ctrlSock.recv(1024) # self.log.info('receving data of file is : {:.2f}%'.format(recvedFileSize / filesize * 100)) f.write(recvfile) # self.log.info('start recv {} loop'.format(i)) # self.log.info('this task need to loop {}, the last info size of info is : {}'.format(loop, extend)) self.signal.recv.emit(1) # self.log.info('emit 1') recvedFileSize += len(recvfile) # self.ctrlSock.send(b'1') # receiving file recvfile = self.ctrlSock.recv(extend) f.write(recvfile) self.signal.recv.emit(0) # self.log.info('save size:{}/ file size:{}'.format(os.path.getsize(self.saveFilePath), self.downloadFileInfo['size'])) if utils.calculateHashCodeForFile( self.saveFilePath_E) == self.fileinfo['hashcode']: # self.sslctrlSock.send(b'0') # recv finished self.log.info('download file finished') return (0, 'ok') else: # self.sslctrlSock.send(b'2') # size not match return (1, 'hase code not match') def checkCmdCode(func): def wrapper(self): res = func(self) if self.recvInfo['code'] != self.lastCmdCode: self.log.info('lastCmdCode is not same, login fails') return res return wrapper def setupCmdCode(func): def wrapper(self, msg): self.lastCmdCode = str( utils.generateRandomDigitFromRange(10000, 99999)) # print('*********** send msg len is :{},type is {}, info is {}'.format(len(msg),type(msg),msg)) msg['code'] = self.lastCmdCode return func(self, msg) return wrapper def fillSnedMsg(func): def wrapper(self, msg): msg = str.encode(str(msg)) fillSize = self.SEND_BUFFER_SIZE - len(msg) msg = b''.join((msg, b' ' * fillSize)) # print('resize send msg len is :{},type is {}, info is {}'.format(len(msg),type(msg),msg)) return func(self, msg) return wrapper @setupCmdCode @fillSnedMsg def sendMsg(self, msg): self.lastCmd = msg try: self.ctrlSock.send(msg) except Exception as e: return (1, str(e)) else: self.log.info('send info : {}'.format(msg.strip())) # self.log.info('###########{}##########'.format(msg)) return (0, "ok") @checkCmdCode def recvMsg(self): self.log.info('perpare recv info') tmpRecvInfo = b'' try: recvInfo = self.ctrlSock.recv(1024).strip() except socket.timeout as e: return (1, str(e)) except Exception as e: return (1, str(e)) if len(recvInfo) == 0: return (1, 'can\'t recevie info') tmpRecvInfo += recvInfo while len(recvInfo) == int(self.settings.default.recv_cmd_buffer_size ) or str(recvInfo)[-2] != '}': self.log.info( 'recv length of info is over default length, start recv extend info' ) try: recvInfo = self.ctrlSock.recv(1024).strip() except Exception as e: return (1, str(e)) else: tmpRecvInfo += recvInfo self.recvInfo = utils.rebuildDictFromBytes(tmpRecvInfo) self.log.info('recv info {}'.format(self.recvInfo)) return (0, "ok") def recvMark(self): try: recvInfo = self.ctrlSock.recv(1).strip() except Exception as e: self.log.info(' recv upload file transfer mark error : {}'.format( str(e))) else: # self.recvInfo = literal_eval(recvInfo.decode('utf8')) # self.log.info('recv info {}'.format(recvInfo.strip())) return recvInfo def logout(self): pass def reconnect(self): pass def close(self): self.ctrlSock.shutdown(socket.SHUT_RDWR) self.ctrlSock.close() @staticmethod def test(): print('host')
def __init__(self): super(Status, self).__init__() self.log = Syslog()
def init_log(self): self.log = Syslog()
class Action_MainWindow(QMainWindow, Ui_MainWindow): """docstring for Action_MainWindow.""" def __init__(self): QMainWindow.__init__(self) self.setupUi(self) # self.Setlist.triggered.connect(self.setlist) # self.Download_2.triggered.connect(self.test) self.client = None self.loginStatus = False self.upload_dialog = None self.download_dialog = None # self.Infolist.scrollToBottom() def start(self): self.init_configure() self.init_folder() self.init_log() self.init_signal() self.init_ui_setting() self.show() def init_configure(self): """Pass.""" # self.log.info('start init configure file') if not utils.checkFileExists(utils.getenv('COWRY_CONFIG')): src = utils.joinFilePath(utils.getenv('COWRY_ROOT'), 'cowry.conf.default') dst = utils.joinFilePath(utils.getenv('COWRY_ROOT'), 'cowry.conf') utils.copyfile(src, dst) print('Not find default configure file, copy default configure to use') self.settings = Settings() # set default certificates folders values if not self.settings.certificates.certdirs: setDefaultCertDirs = utils.joinFilePath(utils.getenv('COWRY_ROOT'), 'certs') self.settings._set(('certificates', 'certdirs', setDefaultCertDirs)) def init_folder(self): # create upload folders if not utils.checkFolderExists(self.settings.certificates.certdirs): try: utils.makeDirs(self.settings.certificates.certdirs) except Exception as e: self.log.error('certs folder create error : {}'.format(str(e))) def init_log(self): self.log = Syslog() def init_signal(self): self.actionloadLoginInfo.triggered.connect(self.setdefaultinfo) self.actiondeleteCertificate.triggered.connect(self.deleteCerts) self.actionview_cert_info.triggered.connect(self.view_cert_info) self.actionimport_cert.triggered.connect(self.import_cert) self.Encrypts.currentIndexChanged.connect(self.setEncryptStatus) self.Usepassword.clicked.connect(self.setCiphercode) def init_ui_setting(self): if self.Encrypts.currentText() == 'None': self.Ciphercode.hide() self.Label_cipher.hide() self.Usepassword.hide() self.Button_encrypt.hide() self.Ciphercode.setEnabled(False) self.Ciphercode.setText(self.Password.text()) self.Usepassword.setChecked(True) self.Filetree_Public.header().resizeSection(2,0) self.Filetree_Private.header().resizeSection(2,0) def auth(func): def wrapper(self): if self.loginStatus != True: self.Infolist.addItem('please login system !!!') else: func(self) self.Infolist.scrollToBottom() return wrapper @auth def setEncryptStatus(self): if self.Encrypts.currentText() == 'None': self.Ciphercode.hide() self.Label_cipher.hide() self.Usepassword.hide() self.Button_encrypt.hide() self.client.encryption = False self.Infolist.addItem("Close Local Files Model Of Encryption") else: self.Ciphercode.show() self.Label_cipher.show() self.Usepassword.show() self.Button_encrypt.show() self.setCiphercode() @auth def setCiphercode(self): if self.Usepassword.isChecked(): self.Ciphercode.setEnabled(False) self.Ciphercode.setText(self.Password.text()) else: self.Ciphercode.setText('') self.Ciphercode.setEnabled(True) def getinfo(self): # QtWidgets.QMessageBox.information(self.pushButton,"标题","这是第一个PyQt5 GUI程序") msg = QtWidgets.QMessageBox() msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("This is a message box") msg.setInformativeText("This is additional information") msg.setWindowTitle("MessageBox demo") msg.setDetailedText("The details are as follows:") msg.setStandardButtons(QtWidgets.QMessageBox.Ok | QtWidgets.QMessageBox.Cancel) retval = msg.exec_() self.log.info("value of pressed message box button: {}".format(retval)) def quit(self): reply = QMessageBox.question(self, 'Message', "Are you sure to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: if self.loginStatus is True: self.logout() self.close() else: print("2333") def login(self): if self.loginStatus is True: self.logout() self.Filetree_Private.clear() vhost = str(self.Host.text().strip()) vport = int(str(self.Port.text().strip()) or '0') vusername = str(self.Username.text().strip()) vpassword = str(self.Password.text().strip()) if not vhost or not vport or not vusername or not vpassword: self.Infolist.addItem('please input connecting info') else: self.client = FTPClient(host=vhost, port=vport, username=vusername, password=vpassword) ret = self.client.createConnection() if ret[0] == 1: self.Infolist.addItem(str(ret[1])) self.Infolist.scrollToBottom() else: self.client.signal.refresh.connect(self.refresh) loginInfo = self.client.login() if loginInfo[0] == 0: self.Infolist.addItem(str(loginInfo[1])) self.Infolist.addItem(str().join(('Encryption with : ', loginInfo[2][2:29]))) self.client.id = loginInfo[3] self.loginStatus = True status = str().join(('密钥协商:', loginInfo[2][2:11],'数据加密:',loginInfo[2][12:22],'数据签名:',loginInfo[2][23:29])) self.statusBar.showMessage(status) self.refresh() else: # print(type(loginInfo),type(loginInfo[1]), loginInfo) self.Infolist.addItem(loginInfo[1]) # self.client.close() self.Infolist.scrollToBottom() @auth def logout(self): logoutInfo = self.client.logout() if logoutInfo[0] == 0: self.Infolist.addItem(logoutInfo[1]) self.Filetree_Private.clear() self.loginStatus = False else: self.Infolist.addItem(logoutInfo[1]) def reconnect(self): self.log.info('start reconnect') self.Filetree_Private.clear() if self.loginStatus is True: self.logout() self.login() self.Infolist.scrollToBottom() @auth def upload(self): try: retInfo = QFileDialog.getOpenFileName(self, 'Open upload file', utils.getUserHome()) except Exception as e: self.log.info(e) if retInfo[0]: filepath = retInfo[0] filename = utils.getBaseNameByPath(filepath) self.log.info('prepare file :{}'.format(filepath)) self.upload_dialog = QtWidgets.QDialog() self.upload_dialog.ui = Ui_UploadFileDialog() self.upload_dialog.comfirm = self.client.uploadComfirm self.upload_dialog.ui.setupUi(self.upload_dialog) self.upload_dialog.ui.Filename.setText(filename) self.upload_dialog.ui.Progress.setValue(0) self.client.upbar = self.upload_dialog retInfo = self.client.upload(filepath) if retInfo[0] == 0: self.upload_dialog.show() self.Infolist.addItem('file is uploading') else: self.Infolist.addItem(retInfo[1]) @auth def download(self): if self.tabWidget.currentIndex() == 0: selectFiles = self.Filetree_Private.selectedItems() else: selectFiles = self.Filetree_Public.selectedItems() # currentTab = self.tabWidget.currentTabText if not selectFiles: self.Infolist.addItem('Please select file') else: # self.log.info('selected file is : {}'.format(selectFiles) # self.log.info('index : {}'.format(self.Filetree_Private.selectedIndexes())) downloadFileInfo = {} downloadFileInfo['filename'] = selectFiles[0].text(0) downloadFileInfo['postfix'] = selectFiles[0].text(1) downloadFileInfo['filehash'] = selectFiles[0].text(2) downloadFileInfo['encryption_type'] = selectFiles[0].text(4) downloadFileName = str().join((downloadFileInfo['filename'], '.', downloadFileInfo['postfix'])) # check the download file whether need to decrypt # if not, alert info of open encryption option if downloadFileInfo['encryption_type'] != 'No' and not self.client.encryption: self.Infolist.addItem('The file to be downloaded has been encrypted, you must open encrypt option!') else: try: retInfo = QFileDialog.getSaveFileName(self, 'Save download file', downloadFileName) except Exception as e: raise if retInfo[0]: downloadFilePath = retInfo[0] # # filename = os.path.basename(filepath) self.log.info('start draw download progress GUI') self.download_dialog = QtWidgets.QDialog() self.download_dialog.ui = Ui_DownloadFileDialog() self.download_dialog.comfirm = self.client.downloadComfirm self.download_dialog.ui.setupUi(self.download_dialog) self.download_dialog.ui.Filename.setText(downloadFileName) self.download_dialog.ui.Progress.setValue(0) self.download_dialog.show() self.client.dpbar = self.download_dialog retInfo = self.client.download(downloadFileInfo['filehash'], downloadFilePath) if retInfo[0] == 0: self.Infolist.addItem('file download successd') else: self.download_dialog.close() self.Infolist.addItem(retInfo[1]) @auth def refresh(self): self.Filetree_Private.clear() self.Filetree_Public.clear() listInfo = self.client.list() # start files list # fileList = self.client.list('/') if listInfo[0] == 0: fileList = QtWidgets.QTreeWidgetItem([" /"]) if listInfo[1] and isinstance(listInfo[1], list): for file in listInfo[1]: if file['encryption'] == 1: encryption = file['encryption_type'] else: encryption = 'No' if str(file['uid']) != str(self.client.id) or file['is_delete'] == 1: continue if str(file['public']) == '1': is_public = 'Yes' else: is_public = 'No' fileItem = QtWidgets.QTreeWidgetItem([file['name'], file['postfix'][1:], file['hashcode'], utils.prettySize(file['size']), encryption, file['updatetime'], is_public ]) fileList.addChild(fileItem) self.Filetree_Private.addTopLevelItem(fileList) self.Filetree_Private.expandToDepth(0) # refresh Public public_fileList = QtWidgets.QTreeWidgetItem([" /"]) for file in listInfo[1]: if file['encryption'] == 1: encryption = file['encryption_type'] else: encryption = 'No' if str(file['public']) != '1': continue fileItem = QtWidgets.QTreeWidgetItem([file['name'], file['postfix'][1:], file['hashcode'], utils.prettySize(file['size']), encryption, file['updatetime'] ]) public_fileList.addChild(fileItem) self.Filetree_Public.addTopLevelItem(public_fileList) self.Filetree_Public.expandToDepth(0) # end self.Infolist.addItem("Refresh Completed") else: self.Infolist.addItem(str(listInfo[1])) @auth def encrypt(self): # if self.Usepassword.clicked(): # self.log.info('current select item is : {}'.format(self.Encrypts.currentText())) self.client.encryption = True self.client.encryption_type = str(self.Encrypts.currentText().strip()) self.client.encryption_cipher = str(self.Ciphercode.text().strip()) self.Infolist.addItem("Open Local Files Model Of Encryption") def keyPressEvent(self, e): if e.key() == Qt.Key_Escape: self.quit() def setdefaultinfo(self): self.Host.setText('0.0.0.0') self.Port.setText('2333') self.Username.setText('aong') self.Password.setText('1234') def deleteCerts(self): if utils.delFilesFromFolder(self.settings.certificates.certdirs): self.Infolist.addItem("Delete All Certificates In System Successd.") def setlist(self): self.step += 1 # fileList = QtWidgets.QTreeWidgetItem([" /"]) # # if listInfo[1] and type(listInfo[1]) is list: # # for file in fileList[1]: # fileItem = QtWidgets.QTreeWidgetItem(['1','2','3','4']) # fileList.addChild(fileItem) # self.Filetree_Private.addTopLevelItem(fileList) # self.upload_dialog.UploadProgress.setValue(50) self.upload_dialog.ui.UploadProgress.setValue(self.step) def openmenu(self, position): indexes = self.Filetree_Private.selectedIndexes() if len(indexes) > 0: level = 0 index = indexes[0] while index.parent().isValid(): index = index.parent() level += 1 menu = QMenu(self) if level == 0: # menu.addAction(self.tr("Edit person")) pass elif level == 1: selectFile = self.Filetree_Private.selectedItems() Items = ['delete', 'transfer', 'open', 'close_open'] for item in Items: if item == 'open' and selectFile[0].text(6) == 'Yes': continue if item == 'close_open' and selectFile[0].text(6) != 'Yes': continue action = QAction(item, self) action.triggered.connect(getattr(self, 'file_{}'.format(item))) menu.addAction(action) elif level == 2: menu.addAction(self.tr("Edit object")) menu.exec_(self.Filetree_Private.mapToGlobal(position)) @auth def file_transfer(self): selectFile = self.Filetree_Private.selectedItems() filehash = selectFile[0].text(2) filename = str().join((selectFile[0].text(0), '.', selectFile[0].text(1))) # get user email to transfer Ui_Transfer_File # vhost = str(self.Host.text().strip()) def sure(): target_email = str(self.transferfile_dialog.ui.Transfer_Email.text().strip()) self.log.info("start transfer : {} to :{}".format(filename, target_email)) retInfo = self.client.transfer_file(target_email, filehash) self.transferfile_dialog.close() self.Infolist.addItem(retInfo[1]) self.Infolist.scrollToBottom() self.refresh() self.transferfile_dialog = QtWidgets.QDialog() self.transferfile_dialog.ui = Ui_Transfer_File() self.transferfile_dialog.accept = sure self.transferfile_dialog.ui.setupUi(self.transferfile_dialog) self.transferfile_dialog.ui.Transfer_Filename.setText(filename) self.transferfile_dialog.show() @auth def file_delete(self): selectFiles = self.Filetree_Private.selectedItems() filehash = selectFiles[0].text(2) reply = QMessageBox.question(self, 'Message', "Are you sure to delete this file?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: retInfo = self.client.delete_file(filehash) # self.openfile_dialog.close() self.Infolist.addItem(retInfo[1]) self.Infolist.scrollToBottom() self.refresh() else: self.log.info('cancel delete file') @auth def file_open(self): def sure(): selectFile = self.Filetree_Private.selectedItems() self.log.info("open file : ".format(selectFile[0].text(2))) retInfo = self.client.open_file(selectFile[0].text(2)) self.openfile_dialog.close() self.Infolist.addItem(retInfo[1]) self.Infolist.scrollToBottom() self.refresh() self.openfile_dialog = QtWidgets.QDialog() self.openfile_dialog.ui = Ui_Open_File() self.openfile_dialog.accept = sure self.openfile_dialog.ui.setupUi(self.openfile_dialog) self.openfile_dialog.show() @auth def file_close_open(self): def sure(): selectFile = self.Filetree_Private.selectedItems() self.log.info("close file : ".format(selectFile[0].text(2))) retInfo = self.client.close_file(selectFile[0].text(2)) self.closefile_dialog.close() self.Infolist.addItem(retInfo[1]) self.Infolist.scrollToBottom() self.refresh() self.closefile_dialog = QtWidgets.QDialog() self.closefile_dialog.ui = Ui_Close_File() self.closefile_dialog.accept = sure self.closefile_dialog.ui.setupUi(self.closefile_dialog) self.closefile_dialog.show() @auth def view_cert_info(self): certificate_name = str(self.Host.text().strip()) + '.crt' cert_info = utils.getCertInfo(utils.joinFilePath(self.settings.certificates.certdirs, certificate_name)) def sure(): self.certInfo_dialog.close() self.certInfo_dialog = QtWidgets.QDialog() self.certInfo_dialog.ui = Ui_Cert_Info() self.certInfo_dialog.accept = sure self.certInfo_dialog.ui.setupUi(self.certInfo_dialog) self.certInfo_dialog.ui.Signature.setText(cert_info['digest']) self.certInfo_dialog.ui.Filehash.setText(cert_info['filehash']) self.certInfo_dialog.show() @auth def import_cert(self): pass
def __init__(self): super(Cryptogram, self).__init__() self.log = Syslog()
class Cryptogram(object): """docstring for Cryptogram.""" def __init__(self): super(Cryptogram, self).__init__() self.log = Syslog() def encrypt_text(self, string, key, mode='AES-128-CBC'): CKey = self.convertKey(string, mode) rsa_key = RSA.importKey(key) c = rsa_key.encrypt(CKey.encode(), 'a') cb64 = base64.b64encode(c[0]) return (0, cb64) def decrypt_text(self, string, key): rsa_key = RSA.importKey(key) c = base64.b64decode(string) p = rsa_key.decrypt(c).decode() return (0, p) def encrypt(self, key, filepath, mode='AES-128-CBC'): self.log.info('prepare encrypt file : {} \nuse mode is :{} \n, Cipher is :{} '.format(filepath, mode, key)) try: encrypt_with_mode = getattr(self, 'encrypt_file_with_' + C_TYPE[mode]['F']) except Exception as e: raise else: CKey = self.convertKey(key, mode) # CKey = key return encrypt_with_mode(CKey, filepath) def decrypt(self, key, filepath, savefilepath, nck=0, mode='AES-128-CBC'): self.log.info('prepare decrypt file : {} \nuse mode is :{} \n, Cipher is :{} '.format(filepath, mode, key)) try: decrypt_with_mode = getattr(self, 'decrypt_file_with_' + C_TYPE[mode]['F']) except Exception as e: raise else: if nck == 0: CKey = self.convertKey(key, mode) else: CKey = key self.log.info(CKey) # CKey = key return decrypt_with_mode(CKey, filepath, out_filename=savefilepath) def convertKey(self, key, mode): cipherLength = C_TYPE[mode]['C_L'] # 128 hashcode = hashlib.sha512(str.encode(key)).hexdigest() newKey = hashcode[0:cipherLength] return newKey @staticmethod def encrypt_file_with_aes_cbc(key, in_filename, out_filename=None, chunksize=64*1024): # """Encrypts a file using AES (CBC mode) with the # given key. # # key: # The encryption key - a string that must be # either 16, 24 or 32 bytes long. Longer keys # are more secure. # # in_filename: # Name of the input file # # out_filename: # If None, '<in_filename>.enc' will be used. # # chunksize: # Sets the size of the chunk which the function # uses to read and encrypt the file. Larger chunk # sizes can be faster for some files and machines. # chunksize must be divisible by 16. # """ if not out_filename: baseName = os.path.basename(in_filename) out_filename = '/tmp/' + baseName + '.enc' # iv = os.urandom(16) iv = b'0000000000000000' encryptor = AES.new(key, AES.MODE_CBC, iv) filesize = os.path.getsize(in_filename) with open(in_filename, 'rb') as infile: with open(out_filename, 'wb') as outfile: outfile.write(struct.pack('<Q', filesize)) outfile.write(iv) while True: chunk = infile.read(chunksize) if len(chunk) == 0: break elif len(chunk) % 16 != 0: chunk += b' ' * (16 - len(chunk) % 16) outfile.write(encryptor.encrypt(chunk)) enc_filepath = os.path.abspath(out_filename) return (0, enc_filepath) @staticmethod def decrypt_file_with_aes_cbc(key, in_filename, out_filename=None, chunksize=24*1024): # """ Decrypts a file using AES (CBC mode) with the # given key. Parameters are similar to encrypt_file, # with one difference: out_filename, if not supplied # will be in_filename without its last extension # (i.e. if in_filename is 'aaa.zip.enc' then # out_filename will be 'aaa.zip') # """ if not out_filename: out_filename = os.path.splitext(in_filename)[0] with open(in_filename, 'rb') as infile: origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0] iv = infile.read(16) decryptor = AES.new(key, AES.MODE_CBC, iv) with open(out_filename, 'wb') as outfile: while True: chunk = infile.read(chunksize) if len(chunk) == 0: break try: outfile.write(decryptor.decrypt(chunk)) except Exception as e: return (1, str(e)) outfile.truncate(origsize) # dec_filepath = os.path.abspath(out_filename) return (0, "ok")
class BaseSocket(object): """docstring for Client.""" def __init__(self, **arg): super(BaseSocket, self).__init__() # self.clientSocket = clientSocket # self.clientAddress = clientAddress self.log = Syslog() self.settings = Settings() self.SEND_CMD_BUFFER_SIZE = self.settings['DEFAULT'].getint( 'SEND_CMD_BUFFER_SIZE') self.SEND_FILE_BUFFER_SIZE = self.settings['DEFAULT'].getint( 'SEND_FILE_BUFFER_SIZE') self.RECV_CMD_BUFFER_SIZE = self.settings['DEFAULT'].getint( 'RECV_CMD_BUFFER_SIZE') self.__dict__.update(arg) msgCode = ('login', 'logout', 'refresh', 'list', 'get', 'put') def fillSnedMsg(func): def wrapper(self, msg): msg = str.encode(str(msg)) msgLentgh = len(msg) if msgLentgh <= self.SEND_CMD_BUFFER_SIZE: fillSize = self.SEND_CMD_BUFFER_SIZE - msgLentgh msg = b''.join((msg, b' ' * fillSize)) # print('resize send msg len is :{},type is {}, info is {}'.format(len(msg),type(msg),msg)) self.log.info('perpare send recall info : {}'.format(msg)) return func(self, msg) else: loops = msgLentgh // self.SEND_CMD_BUFFER_SIZE extendLentgh = msgLentgh % self.SEND_CMD_BUFFER_SIZE for i in range(loops): self.log.info( 'perpare send recall info by {} loops: {}'.format( i, msg[i * self.SEND_CMD_BUFFER_SIZE:self. SEND_CMD_BUFFER_SIZE * (i + 1)])) retInfo = func( self, msg[i * self.SEND_CMD_BUFFER_SIZE:self. SEND_CMD_BUFFER_SIZE * (i + 1)]) if retInfo[0] == 1: return retInfo fillSize = self.SEND_CMD_BUFFER_SIZE - extendLentgh extendmsg = b''.join( (msg[loops * self.SEND_CMD_BUFFER_SIZE:], b' ' * fillSize)) self.log.info( 'perpare send recall extendmsg : {}'.format(extendmsg)) return func(self, extendmsg) return wrapper @fillSnedMsg def sendMsg(self, msg): self.log.info('prepare send msg size : {} '.format(len(msg))) try: self.clientSocket.send(msg) except Exception as e: return (1, str(e)) else: return (0, "ok") def sendFile(self): with open(self.downloadFilePath, 'rb') as f: try: sendSize = self.clientSocket.sendfile(f) except Exception as e: self.log.info('send file fails : {}'.format(str(e))) else: self.log.info('send file Successd') finally: self.log.info('total send size is :{:.2f} K'.format(sendSize / 1024)) def recvMsg(self): try: info_tmp = self.clientSocket.recv( self.RECV_CMD_BUFFER_SIZE).strip() except Exception as e: return (1, str(e)) else: if len(info_tmp) == 0: self.log.info('recv a null info, close client connecting') return (2, 'a null info') else: try: self.recvInfo = utils.rebuildDictFromBytes(info_tmp) except Exception as e: self.log.info('error info : {}'.format(info_tmp)) return (3, str(e)) else: return (0, "ok") def recvFile(self): self.log.info('######## start recv file ########') loop = self.fileSize // 1024 extend = self.fileSize % 1024 with open(self.uploadFilePath, 'wb') as f: recvedFileSize = 0 for i in range(loop): recvfile = self.clientSocket.recv(self.RECV_CMD_BUFFER_SIZE) # self.log.info('receving data of file is : {:.2f}%'.format(recvedFileSize / filesize * 100)) f.write(recvfile) self.log.info('start recv {} loop'.format(i)) self.log.info( 'this task need to loop {}, the last info size of info is : {}' .format(loop, extend)) recvedFileSize += len(recvfile) self.clientSocket.send(b'1') # receiving file recvfile = self.clientSocket.recv(extend) f.write(recvfile) calculateFileSize = utils.getSizeByPath(self.uploadFilePath) self.log.info('upload file size is : {}'.format(calculateFileSize)) self.log.info('origin file size is : {}'.format(self.fileSize)) if calculateFileSize == self.fileSize: self.clientSocket.send(b'0') # recv finished self.log.info('upload finished') return (0, 'ok') else: self.log.info( 'recved file size is :{}, upload file size is {}'.format( calculateFileSize, self.fileSize)) self.clientSocket.send(b'2') # size not match return (1, 'size not match') def close(self): self.log.info("worker subprocess end") self.clientSocket.shutdown(socket.SHUT_RDWR) self.clientSocket.close() def createSslSock(self): self.log.info('start perpare accept data connecting ......') self.clientSock, self.clientAddress = self.dataSock.accept() self.log.info('recv data connecting, client info is : {}'.format( self.clientAddress)) self.clientSocket = self.sslContext.wrap_socket(self.clientSock, server_side=True) def createDataSock(self): self.log.info('start create data socket') # create an INET, STREAMing socket self.dataSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.dataSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bind the socket to a public host, and a well-known port while True: randomPort = utils.generateRandomDigitFromRange(2333, 2433) try: self.dataSocket.bind( (utils.getenv('COWRY_HOST'), int(randomPort))) except Exception as e: self.log.info(str(e)) else: dataSocketInfo = self.dataSocket.getsockname() self.log.info('data socket create successd on : {}'.format( dataSocketInfo)) break # become a server socket self.dataSocket.listen(1) # return data port return (0, randomPort) def test(self): self.log.info('host')
class Server(): """docstring for Server.""" def __init__(self): """Default model is start, Add some necessary for it.""" super(Server, self).__init__() self.log = None self.settings = None self.ssl = None self.db = None self.systemStatus = None self.serverSocket = None self.defaultConfigPath = None self.init_configure() self.init_log() def init_check(self): """Init check.""" system_python_version = platform.python_version() if float(system_python_version[:-2]) < 3.5: self.log.error( ' Version of python on your system is less than 3.5, \ Cowry software not install here !!') exit() system_type = platform.system() if system_type == 'Linux': self.defaultConfigPath = '/etc/cowry/' elif system_type == 'Darwin': self.defaultConfigPath = '/etc/cowry/' elif system_type == 'Windows': self.defaultConfigPath = 'C:\\cowry' else: self.log.error("can't recognize type of your system, \ Cowry must be installed on Windows, Linux or Darwin system" ) exit() try: # os.stat(self.defaultConfigPath) pass except FileNotFoundError: try: pass # os.mkdir(self.defaultConfigPath) except Exception as e: self.log.error(str(e)) def init_db(self): """Pass.""" self.db = Db() def init_configure(self): """Pass.""" # self.log.info('start init configure file') if not utils.checkFileExists(utils.getenv('COWRY_CONFIG')): src = utils.joinFilePath(utils.getenv('COWRY_ROOT'), 'cowry.conf.default') dst = utils.joinFilePath(utils.getenv('COWRY_ROOT'), 'cowry.conf') utils.copyfile(src, dst) print( 'Not find default configure file, copy default configure to use' ) self.settings = Settings() # set default uploaded files path if not utils.checkAbsPath( self.settings.storage.datapath) or not utils.checkFolderExists( self.settings.storage.datapath): setDefaultDataPath = utils.joinFilePath(utils.getenv('COWRY_ROOT'), 'data') self.settings._set(('storage', 'datapath', setDefaultDataPath)) # set default certificates values if not utils.checkAbsPath(self.settings.certificates.privatekey ) and not utils.checkAbsPath( self.settings.certificates.certificate): setDefaultPrivateKey = utils.joinFilePath( utils.getenv('COWRY_ROOT'), 'certs', 'server.key') setDefaultCert = utils.joinFilePath(utils.getenv('COWRY_ROOT'), 'certs', 'server.crt') self.settings._set( ('certificates', 'privatekey', setDefaultPrivateKey)) self.settings._set(('certificates', 'certificate', setDefaultCert)) # set db default path if sqlite be used if self.settings.database.type == 'sqlite' and not self.settings.database.df: setDefaultSqliteDbPath = utils.joinFilePath( utils.getenv('COWRY_ROOT'), 'db', 'data', 'default.sqlite') self.settings._set(('database', 'df', setDefaultSqliteDbPath)) def init_folder(self): """Pass.""" # create upload folders if not utils.checkFolderExists(self.settings.storage.datapath): try: utils.makeDirs(self.settings.storage.datapath) except Exception as e: self.log.error('upload folder create : {}'.format(str(e))) # create certs folders cert_dir_name = utils.getDirNameByPath( self.settings.certificates.privatekey) if not utils.checkFolderExists(cert_dir_name): try: utils.makeDirs(cert_dir_name) except Exception as e: self.log.error('cert folder create : {}'.format(str(e))) # create database folders if system use sqlite if self.settings.database.type == 'sqlite': db_dir_name = utils.getDirNameByPath(self.settings.database.df) if not utils.checkFolderExists(db_dir_name): utils.makeDirs(db_dir_name) if not utils.checkFolderExists(db_dir_name): try: utils.makeDirs(db_dir_name) except Exception as e: self.log.error('db folder create : {}'.format(str(e))) def init_log(self): """Pass.""" self.log = Syslog() def init_status(self): """Pass.""" if utils.getenv('COWRY_STATUS') != 'NO': self.systemStatus = Status() self.systemStatus.start() else: self.log.info('Start system without echo status of system.') def init_web_console(self): # up redis # set app root path into redis # if utils.getenv('COWRY_WEB_CONSOLE') == 'YES': self.log.info('start init server web console') WebConsole.start() def init_ssl(self): self.ssl = SSLCertSetting() # check if the certificate exists, if not, sysytem should be auto generate a new certificate if not utils.checkFileExists( self.settings.certificates.privatekey ) and not utils.checkFileExists( self.settings.certificates.certificate): # generate new certificate # check if settings have bind doamin if utils.verifyDomain(self.settings.server.bind_domain): # a server domain is valid in configure file # the server will use this domain to generate a new certificate self.ssl.create_self_signed_cert( self.settings.server.bind_domain) elif self.settings.server.bind_address: self.ssl.create_self_signed_cert(self.settings.certificates.cn) else: self.log.error( "can't read valid domain or IP adress from configure file, create a new certificate need it" ) # set key own os.chmod(path=self.settings.certificates.privatekey, mode=stat.S_IRUSR) # start load certificate # verify certificates if self.ssl.validate_ssl_cert(): self.sslContext = ssl.create_default_context( ssl.Purpose.CLIENT_AUTH) self.log.info('start load certificates: {}'.format( self.settings.certificates.certificate)) self.sslContext.load_cert_chain( certfile=self.settings.certificates.certificate, keyfile=self.settings.certificates.privatekey) else: exit() def init_socket(self): self.log.info('start init server socket') # create an INET, STREAMing socket self.serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # bind the socket to a public host, and a well-known port self.serverSocket.bind((self.settings.server.bind_address, int(self.settings.server.bind_port))) # become a server socket self.serverSocket.listen(5) def init_redis(self): if self.settings.default.cluster == '0': # redis_host = '127.0.0.1' return 0 else: redis_host = self.settings.redis.host self.r = redis.Redis(host=redis_host, port=int(self.settings.redis.port), db=int(self.settings.redis.db)) for i in range(3): if self.r.ping() == True: continue else: time.sleep(1) if i == 3: self.log.error('can\'t connect redis server') exit() self.r.set('master_status', '1') def init_setenv(self): # set host name if utils.verifyDomain(self.settings.server.bind_domain): utils.setenv('COWRY_HOST', self.settings.server.bind_domain) self.log.info('system bind server name on : {}'.format( utils.getenv('COWRY_HOST'))) else: utils.setenv('COWRY_HOST', self.settings.server.bind_address) self.log.info('system bind server name on : {}'.format( utils.getenv('COWRY_HOST'))) def new(self): if self.settings.default.inited != '0': print('System has been inited !!') exit() self.log.info('Start congfigure a new cowry sysytem ...') self.init_folder() self.init_db() self.db.new() self.settings._set(('default', 'inited', '1')) self.log.info('Congfigure completed, watting for start up ...') def start(self): if self.settings.default.inited != '1': print('Please initialization system firstly !!!') exit() self.init_db() self.init_ssl() self.init_redis() self.init_socket() self.init_setenv() self.init_web_console() self.init_status() self.log.info('start run server') while True: (clientSocket, clientAddress) = self.serverSocket.accept() self.log.info("{}<=====>{}".format(clientSocket, clientAddress)) try: client = self.sslContext.wrap_socket(clientSocket, server_side=True) except Exception as e: self.log.info(str(e)) else: self.createWorker(client, clientAddress) def drop(self): """Clear system info and delete all info of cowry.""" # check if system been droped # Check that the system has been deleted if self.settings.default.inited == '0': self.log.info('the system has been deleted'.title()) utils.deleteFile(utils.getenv('COWRY_CONFIG')) exit() self.log.info('Start drop cowry system !!! ') # delete uploaded files if utils.checkFolderExists(self.settings.storage.datapath): utils.delfolder(self.settings.storage.datapath) # delete server certificates if utils.checkFileExists(self.settings.certificates.certificate ) or utils.checkFileExists( self.settings.certificates.privatekey): utils.deleteFile(self.settings.certificates.certificate) utils.deleteFile(self.settings.certificates.privatekey) utils.delfolder( utils.getDirNameByPath(self.settings.certificates.privatekey)) # delete all database tables self.init_db() self.db.drop() # delete all database file if use sqlite if self.settings.database.df: utils.deleteFile(self.settings.database.df) utils.delfolder(utils.getDirNameByPath(self.settings.database.df)) # delete configure file utils.deleteFile(utils.getenv('COWRY_CONFIG')) self.log.info('Finished drop cowry system') exit() def createWorker(self, clientSocket, address): # workerId = hashlib.md5(str(address).encode('utf8')).hexdigest() worker = Worker(clientSocket, address, self.db.Session, sslContext=self.sslContext) worker.start()
def init_log(self): """Pass.""" self.log = Syslog()