Exemple #1
0
class CDMAClient(Client):
    """ A CDMA client """
    handlers = []
    chip = ''

    def __init__(self, name, host = 'localhost', port = 10000):
        Client.__init__(self, host, port)
        self.name = name
        self.crypt = Crypt()
        self.handlers = [self.socket, sys.stdin]

    def run(self):
        self.send(sys.argv[1])
        self.chip = self.socket.recv(1024)
        if self.chip == 'NNNN':
            raise ValueError()
        else:
            print 'client ' + self.name + ' got chip ' + self.chip

        while True:
            readable, writeable, ex = select.select(self.handlers, [], [])
            for r in readable:
                if r == sys.stdin:
                    input = raw_input().split(' ')
                    self.socket.send(input[0])
                    addresseeChip = self.socket.recv(1024)
                    self.socket.send(self.crypt.encrypt(addresseeChip, input[1]))
                else:
                    data = r.recv(1024)
                    print 'received: ' + self.crypt.decrypt(self.chip, data)
def write_config(config, config_file=""):
    if len(config) < 3:
        print("Error not enough config vars passed.")
        exit()
    if config_file == "":
        file = open("/home/pi/fireball_camera/config.txt", "w")
    else:
        file = open(config_file, "w")
    for key in config:
        if key == 'cam_pwd':
            try:
                #We ecrypt the cam password if it is not crypted
                c = Crypt()
                temp = c.decrypt(config['cam_pwd'])
            except:
                config['cam_pwd'] = c.encrypt(config['cam_pwd'])

        if key != 'IP':
            if key == 'cam_ip' and config[key] == '192.168.1.88':
                print("skip.")
            else:
                line = key + "=" + str(config[key]) + "\n"
                file.write(line)

    file.close()
    print("Config written.")
Exemple #3
0
class Config():
    """Operations with configuration."""
    def __init__(self):
        from crypt import Crypt
        self.configFile = os.path.expanduser("~/.yatc/yatc.conf")
        self.config = {}
        self.crypt = Crypt()
        logging.info("Config initialized.")

    def createConfig(self):
        file = open(self.configFile, "wb")
        string = self.crypt.encryptString("admuser=%s\n" % getAdmuser())
        file.write(string)
        file.close()

    def read(self):
        """Read config from file."""
        if not os.path.isfile(self.configFile):
            self.createConfig()
        file = open(self.configFile, "rb")
        conf = {} 
        cryptedInfo = file.read()
        info = self.crypt.decryptString(cryptedInfo)
        settings = info.rsplit("\n")
        for line in settings:
            if len(line) > 0:
                attr, value = line.rsplit("=")
                conf[attr] = value
        file.close()
        logging.info("Configuration read.")
        logging.debug(conf)
        self.config = conf

    def write(self):
        """Write config to file."""
        # don't save user if this option unchecked
        if self.config.get("login"):
            if self.config["saveUser"] == 0:
                del self.config["login"]

        # create settings string
        string = ""
        for attr, value in self.config.items():
            string = string + ("%s=%s\n" % (attr, value))
        cryptedLine = self.crypt.encryptString(string)
        # write settings to file
        file = open(self.configFile, "wb")
        file.write(cryptedLine)
        file.close() 
        logging.info("Configuration wrote.")

    def get(self):
        """Get current configuration."""
        logging.info("Configuration is obtained.")
        return self.config

    def put(self, config):
        """Put changed configuration."""
        logging.info("Configuration is updated.")
        self.config = config
def read_config(config_file=""):
    config = {}
    if config_file == "":
        file = open("/home/pi/fireball_camera/config.txt", "r")
    else:
        file = open(config_file, "r")

    for line in file:
        line = line.strip('\n')
        #print (line)
        #Find first index of =
        c = line.index('=')
        config[line[0:c]] = line[c + 1:]
    try:
        test = config['hd']
    except:
        config['hd'] = 0

    if 'cam_pwd' in config:
        try:
            #We decrypt the cam password if it is crypted
            c = Crypt()
            config['cam_pwd'] = c.decrypt(config['cam_pwd'])
        except:
            config['cam_pwd'] = config['cam_pwd']
    else:
        config['cam_pwd'] = 'xrp23q'

    file.close()
    return (config)
Exemple #5
0
 def __init__(self, server, user, hash_login, hash_msg):
     self.SERVER = server
     self.USER = user
     self.HASH_LOGIN = hash_login
     self.HASH_MSG = hash_msg
     self.crypto = Crypt(username=user,
                         password=None,
                         hash_login=hash_login,
                         hash_msg=hash_msg)
Exemple #6
0
 def __init__(self, masterkey, url, notice=False, debug=False):
     self.parser = URLParser(url)
     self.domain = self.parser.getDomain()
     self.notice = notice
     enc = Crypt(masterkey)
     self.public_key = enc.getPublicKey(self.domain)
     self.sqrlreq = SQRLRequest(self.parser, self.public_key)
     unsigned_url = self.sqrlreq.get_url()
     self.signed_url = enc.sign(unsigned_url)
     self.debug = debug
 def test_ed_cycle(self):
     
     for pt, pph in d_values:
         
         c = Crypt(pph)
         u = c.encrypt(pt)
         dc = c.decrypt(u)
         
         print "assert equal: %s == %s" % (dc, str(pt))
         self.assertEqual(dc, str(pt)) 
Exemple #8
0
 def login(self, username, password):
     u = User.find({"username": username})
     hashed_pass = Crypt.hash_pw(password, u["salt"])
     if hashed_pass != u["password"]:
         return None
     ses = Session.find({"username": username})
     if ses:
         return ses["token"]
     token = Crypt.gen_token()
     created = datetime.datetime.now()
     ses = Session({"username": username, "token": token, "created": created})
     ses.save()
     return token
Exemple #9
0
 def encrypt_text(self, gui, password_entry):
     textentry = self.get_current_textview(gui)
     password = password_entry.get_text()
     textbuffer = Gtk.TextBuffer()
     textbuffer = textentry.get_buffer()
     buffer_start = textbuffer.get_start_iter()
     buffer_end = textbuffer.get_end_iter()
     content = textbuffer.get_text(buffer_start, buffer_end, True)
     key = password
     Cipher = Crypt()
     content_crypted = Cipher.encrypt(key, content)
     try:
         textbuffer.set_text(content_crypted)
         textentry.set_buffer(textbuffer)
     except TypeError:
         print("Type Error")
class Announcement:
    def __init__(self, max_clients, db_name, db_host, db_port, secret):
        self.sequence = secret
        self.base64_alt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

        self.db = Db(self, db_name, db_host, db_port)
        self.announces = self.db.load_announces()
        self.announces_time = int(time.time())

        log.msg('Announcement __init__')
        log.msg(self.announces)

        self.crypt = Crypt(self.sequence)

    def get_announce(self, protocol, game_name):
        result = self.announces.get(game_name, {'result': '0'})

        j = json.dumps(result)
        c = self.crypt.crypt(j)

        log.msg('Send data to client')
        protocol.writeData(c)
        protocol.transport.loseConnection()

        # refresh announces
        if int(time.time()) - self.announces_time > 15:
            self.announces = self.db.load_announces()
            log.msg('Announces updated')
            self.announces_time = int(time.time())
Exemple #11
0
    def from_dict(cls, config):
        cls.public_key = config['public_key']
        cls.address = str(
            P2PKHBitcoinAddress.from_pubkey(cls.public_key.decode('hex')))

        cls.private_key = config['private_key']
        cls.username = config['username']
        cls.wif = cls.to_wif()
        cipher = Crypt(str(cls.private_key))
        cls.bulletin_secret = cls.get_bulletin_secret()

        cls.mongodb_host = config['mongodb_host']
        cls.database = config['database']
        cls.site_database = config['site_database']
        cls.web_server_host = config['web_server_host']
        cls.web_server_port = config['web_server_port']
        if config['peer_host'] == '0.0.0.0' or config[
                'peer_host'] == 'localhost':
            raise Exception(
                "cannot use localhost or 0.0.0.0, must specify public ipv4 address"
            )
        if config['peer_host'] == '[my public ip]':
            raise Exception(
                "please configure your peer_post to your public ipv4 address")
        cls.peer_host = config['peer_host']
        cls.peer_port = config['peer_port']
        cls.serve_host = config['serve_host']
        cls.serve_port = config['serve_port']
        cls.callbackurl = config['callbackurl']
        cls.fcm_key = config['fcm_key']
    def __init__(self, max_clients, db_name, db_host, db_port, secret):
        """
            Constructor.
        """
        # self.server_status = 'not ready'
        self.db_name = db_name
        self.db_host = db_host
        self.db_port = db_port
        # self.db_reconnect()
        self.db = Db(self, self.db_name, self.db_host, self.db_port)

        # Restart DB connection in looping call
        #self.lc = LoopingCall(self.db_reconnect)
        #self.lc.start(300)


        # Sequence bellow showld be the same as on client application
        #self.sequence = [99, 143, 127, 182, 214, 17, 76, 92, 213, 199, 7, 43, 73, 197, 193, 5, 14, 88, 231, 94, 1, 183, 91, 191, 19, 237, 7, 85, 172, 41, 97, 29, 61, 111, 222]
        self.sequence = secret
        self.base64_alt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

        log.msg(secret)

        self.apps = []
        self.clients = {}

        self.max_clients = max_clients

        # self.db = Db(self, db_name, db_host, db_port)
        self.crypt = Crypt(self.sequence)
Exemple #13
0
def specialshift(text, shift1, shift2):
    """letters A-L shift 3, letters
	M-Z shift 5.
	"""

    # shift A-L
    end = text.index('l') + 1
    atol = Crypt.shift(text, shift1)
    atol = atol[:end]

    # shift M-Z
    start = text.index('m')
    mtoz = Crypt.shift(text, shift2)
    mtoz = mtoz[start:]

    domain = atol + mtoz
    return domain
def add_to_config(param,new_value):
    #Read Current Config
    
    if(param!='cam_pwd'):
    
        config = read_config_raw();
        
        logging.debug('Try to update the config file with ' +  str(param) + ' = ' + str(new_value))
        
        updated = 0;
        
        #Loop throught config
        for key in config:
            
            if(key == param):
                config[key] = new_value
                updated = 1;
        
        # In case the param doesnt exist yet in the config file
        if(updated==0):
            config[param] = new_value
            logging.debug('The parameter ' + str(param) + ' didnt exist in config.txt')
            
        # We rewrite the config file
        # WARNING: we need to recrypt cam_pwd here as read_config_raw decrypt it   
        
        file = open("/home/pi/fireball_camera/config.txt", "w")
        
        for key in config:
            value = config[key]
            
            if(key=='cam_pwd'):
                c     = Crypt()
                value = c.encrypt(value)

            if(key!='error'):    
                line = str(key) + "=" + str(value) + "\n"
                file.write(line) 
                   
        file.close()
        
    else:
        logging.error('We tried to update cam_pwd with add_to_config: IMPOSSIBLE')
    def __init__(self, max_clients, db_name, db_host, db_port, secret):
        self.sequence = secret
        self.base64_alt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

        self.db = Db(self, db_name, db_host, db_port)
        self.announces = self.db.load_announces()
        self.announces_time = int(time.time())

        log.msg('Announcement __init__')
        log.msg(self.announces)

        self.crypt = Crypt(self.sequence)
def remove_from_config(param):
    
    config = read_config_raw(); 
    i=0

    while i < len(param):
      if(param[i] in config):
        del config[param[i]]
      i += 1  
 
    file = open("/home/pi/fireball_camera/config.txt", "w")
    for key in config:
        value = config[key]
            
        if(key=='cam_pwd'):
            c     = Crypt()
            value = c.encrypt(value)
            
        line = str(key) + "=" + str(value) + "\n"
        file.write(line) 
                   
    file.close()
def read_config():

    logging.debug('Reading Config.txt')
    config = {}
    
    try: 
        file = open("/home/pi/fireball_camera/config.txt", "r")
        
        for line in file:
          line = line.strip('\n')
          
          #Find first index of =
          if('=' in line):
              c = line.index('=')
              config[line[0:c]] = line[c+1:]
        
        config['hd'] = 0
        
        if 'cam_pwd' in config:
            
            try:
                #We decrypt the cam password if it is crypted
                c = Crypt() 
                config['cam_pwd']  = c.decrypt(config['cam_pwd'])
                logging.debug('cam_pwd successfully decrypted')
            except:
                config['error'] = "Impossible to decrypt the password - password must only contains characters and digits"
                logging.error('Impossible to decrypt ' +  str(config['cam_pwd']))
                logging.debug('Config (ERROR) ' + str(config))
                
        file.close()
        logging.debug('Result ' + str(config) )
        
        return(config)
    except:
        config['error'] = 'The config file cannot be read, please check your config.txt file';
        logging.error('Error in config.txt')
        logging.debug('Config (ERROR) ' + str(config))
    return config;
Exemple #18
0
    def _write(self):
        pos = 0
        # write data entries first
        for key in self.files:
            fi = self.files[key]

            # read data
            f = open(fi.datafile, 'rb')
            data = f.read()
            f.close()

            fi._crc = crc32(data) & 0xffffffff
            fi._uncompressed_length = len(data)

            # check for extension
            _, extension = os.path.splitext(fi.filename)
            if extension in UNCOMPRESSED_EXT:
                # write data uncompressed
                fi._compressed_length = fi.uncompressed_length
            else:
                # compress data
                deflater = zlib.compressobj(6, zlib.DEFLATED, -15)
                data = deflater.compress(data)
                data += deflater.flush()
                fi._compressed_length = len(data)
                deflater = None

            if self.enable_encryption and fi.supports_encryption():
                data = Crypt().encrypt(data)

            self.file_handle.write(data)

            # update file info
            fi._data_offset = pos
            pos += fi.compressed_length

        self._filetable_offset = pos

        # write the file table
        for key in self.files:
            fi = self.files[key]
            buf = fi.to_buffer()
            self.file_handle.write(buf)
            pos += len(buf)

        # write archive footer
        buf = struct.pack('<HIHI4sII', len(self.files), self._filetable_offset, 0, pos, SUPPORTED_FORMATS[0], self.base_revision, self.revision)
        self.file_handle.write(buf)
Exemple #19
0
 def write_config(cls, server, username, password):
     """ Write config file and save modification time
     """
     log.debug(
         f"Writing config file: {server} {username} {password} {cls.VERIFY_SSL_CERT}"
     )
     crypto = Crypt(username, password)
     cls.PATH_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
     cls.PATH_CONFIG_FILE.touch(exist_ok=True)
     config = configparser.ConfigParser()
     config["settings"] = {
         "server": server,
         "username": username,
         "hash_login": crypto.pw_hash_login,
         "hash_msg": crypto.pw_hash_msg,
         "verify_ssl_cert": cls.VERIFY_SSL_CERT,
     }
     with open(cls.PATH_CONFIG_FILE, "w") as configfile:
         config.write(configfile)
     if not cls.CONFIGFILE_MTIME:
         cls.CONFIGFILE_MTIME = Path(cls.PATH_CONFIG_FILE).stat().st_mtime
     return True
Exemple #20
0
 def login(server, user, pw):
     """
     authenticate user using hash generated from pw
     """
     crypto = Crypt(user, pw)
     login_hash = crypto.pw_hash_login
     try:
         res = requests.get(
             server + Config.API_LOGIN,
             auth=(user, login_hash),
             timeout=Config.CONN_TIMEOUT,
             verify=Config.VERIFY_SSL_CERT,
             headers=Config.HEADERS,
         )
     except requests.exceptions.RequestException as e:
         log.exception("Error in login request")
         raise LoginException(e)
     if res.status_code >= 200 and res.status_code < 400:
         log.info("Login successful")
         return True
     else:
         log.error(f"Login failed: {res.status_code} - {res.text}")
         raise LoginException(res.text[0:Config.MAX_RESPONSE_LEN])
Exemple #21
0
    def get_data(self, filename, archive=None):
        """
        Returns the uncompressed data of `filename` in the archive.

        Args:
            filename: The name of the file.
            archive: The name of the archive. Defaults to the current archive

        Returns:
            A string of uncompressed data.
            If the file could not be found, None is returned.
        """
        info = self.get(filename, archive)
        if info is None:
            return None
        self.file_handle.seek(info.data_offset)
        data = self.file_handle.read(info.compressed_length)

        if self.enable_encryption and info.supports_encryption():
            data = Crypt().decrypt(data)

        if info.compressed_length == info.uncompressed_length:
            return data
        return zlib.decompress(data, -15)
Exemple #22
0
 def register(server, user, pw):
     """
     register user on server using hash generated from pw
     """
     crypto = Crypt(user, pw)
     login_hash = crypto.pw_hash_login
     payload = {"username": user, "password": login_hash}
     try:
         res = requests.post(
             server + Config.API_REGISTER,
             data=payload,
             timeout=Config.CONN_TIMEOUT,
             verify=Config.VERIFY_SSL_CERT,
             headers=Config.HEADERS,
         )
     except requests.exceptions.RequestException as e:
         log.exception("Error in register request")
         raise RegisterException(e)
     if res.status_code == 201:
         log.info(f"Hi {user}! You are all set.")
         return True
     else:
         log.error(f"Cannot register user: {res.status_code} - {res.text}")
         raise RegisterException(res.text[0:Config.MAX_RESPONSE_LEN])
class Leaderboards:
    """
      Main game class.
    """
    def __init__(self, max_clients, db_name, db_host, db_port, secret):
        """
            Constructor.
        """
        # self.server_status = 'not ready'
        self.db_name = db_name
        self.db_host = db_host
        self.db_port = db_port
        # self.db_reconnect()
        self.db = Db(self, self.db_name, self.db_host, self.db_port)

        # Restart DB connection in looping call
        #self.lc = LoopingCall(self.db_reconnect)
        #self.lc.start(300)


        # Sequence bellow showld be the same as on client application
        #self.sequence = [99, 143, 127, 182, 214, 17, 76, 92, 213, 199, 7, 43, 73, 197, 193, 5, 14, 88, 231, 94, 1, 183, 91, 191, 19, 237, 7, 85, 172, 41, 97, 29, 61, 111, 222]
        self.sequence = secret
        self.base64_alt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'

        log.msg(secret)

        self.apps = []
        self.clients = {}

        self.max_clients = max_clients

        # self.db = Db(self, db_name, db_host, db_port)
        self.crypt = Crypt(self.sequence)

    #def db_reconnect(self):
    #    self.server_status = 'not ready'
    #    self.db = None
    #    self.db = Db(self, self.db_name, self.db_host, self.db_port)


    def _on_db_init_response(self, value, apps):
        """
            Callback for DB initialization function (class Db).
        """
        self.apps = apps
        if len(self.apps):
            self.server_status = 'ready'
            log.msg('DB connection established (updated)')

    def checkServerStatus(self):
        """
            Tis function calls from class LeaderboardsProtocol pn connectionMade method to check
            if server ready to process user data or not.
        """
        if self.server_status != 'ready' or len(self.clients) > self.max_clients:
            return False
        return True

    def initClient(self, client, addr):
        """
            Save connected user data.
        """

        client.client_id = addr.port
        client.host = addr.host

        client.server_status = self.server_status
        client.chunks_amount = None
        client.chunks = None
        client.data = ''


        client.mode = None
        client.game_type = None
        client.max_score = 0
        client.best_item = None
        client.top = []
        client.best_item_place = None


        log_msg = 'class Leadreboards, client %s initialized' % (client.client_id,)
        log.msg(log_msg)

        # Add new client to global dictionary
        self.clients[client.client_id] = client

        return client

    def processUserRecords(self, client_id, data):
        #log.msg('processUserRecords: received data')
        #log.msg(len(data))
        #log.msg(data)

        decoded_data = self.decodeUserRecords(data)

        #log.msg('decrypted')
        #log.msg(decoded_data)

        user_results = json.loads(decoded_data)

        self.clients[client_id].mode = mode = user_results.get('mode', None)
        self.clients[client_id].game_type = game_type = user_results.get('game_type', 'tetcolor')
        app_name = user_results.get('app_name', None)
        app_secret = user_results.get('app_secret', None)
        results = user_results.get('local_records', None)

        # TODO: uncomment this line after update of all clients
        # if game_type is None or mode is None or app_name is None or app_secret is None or results is None:
        if mode is None or app_name is None or app_secret is None or results is None:
            log.msg('Wrong request for %s, %s, %s' % (mode, app_name, app_secret))
            return 'wrong request'

        app_check = False
        for app in self.apps:
            if app['name'] == app_name and app['secret'] == app_secret:
                app_check = True

        if not app_check:
            return 'wrong arguments'

        #log.msg(app_name)
        #log.msg(app_secret)

        import base64

        items = []

        for result in results:
            if isinstance(result, dict):
                name = result.get('name', None)
                score = result.get('value', None)
                record_id = result.get('record_id', None)

                if name is not None and score is not None and record_id is not None:
                    #name = self.crypt(name, True)
                    name = base64.b64decode(name)

                    timestamp = int(time.time())

                    item = {}
                    item['name'] = name
                    item['score'] = score
                    item['timestamp'] = timestamp
                    item['record_id'] = record_id
                    if self.clients[client_id].game_type != 'tetcolor':
                        item['mode'] = self.clients[client_id].game_type + '_' + mode
                    else:
                        item['mode'] = mode

                    print('current best ' + str(self.clients[client_id].max_score) + '; score ' + str(score))
                    if int(score) > int(self.clients[client_id].max_score):
                        print('set this item as best because ' + str(score) + ' gt ' + str(self.clients[client_id].max_score))
                        self.clients[client_id].max_score = score
                        self.clients[client_id].best_item = item

                    items.append(item)

        self.db.check_unique_and_insert(items, self.clients[client_id].host)\
            .addCallback(self._on_db_insert_response, client_id)\
            .addErrback(self._on_db_error, client_id)

        return 'wait for db'

    def _on_db_insert_response(self, value, client_id):
        """
            Callback for DB insert function (class Db).
        """
        log.msg('Data inserted for client ' + str(client_id))

        self.retrieveTopResults(client_id)

    def retrieveTopResults(self, client_id):
        """
            Retrieve best results from DB and send to client,
        """

        self.db.get_top(client_id, self.clients[client_id].mode, self.clients[client_id].game_type)\
            .addCallback(self._on_db_get_top_response, client_id)\
            .addErrback(self._on_db_error, client_id)

    def _on_db_get_top_response(self, value, client_id):
        #log.msg('top10 number ' + str(len(self.clients[client_id].top)))
        #log.msg(str(self.clients[client_id].top[0]['name']))
        #for result in self.clients[client_id].top:
        #    log.msg('top item: ' + unicode(result['name']) + ' ' + str(result['score']))

        if self.clients[client_id].best_item is None or self.clients[client_id].best_item['score'] is None:
            score = 0
            self.clients[client_id].best_item = {}
            self.clients[client_id].best_item['score'] = 0
            self.clients[client_id].best_item['record_id'] = 'some-unexisting-value'
        else:
            score = self.clients[client_id].best_item['score']

        self.db.get_user_best(client_id, score, self.clients[client_id].mode, self.clients[client_id].game_type)\
            .addCallback(self._on_db_get_user_best_response, client_id)\
            .addErrback(self._on_db_error, client_id)

    def _on_db_get_user_best_response(self, value, client_id):
        log.msg('best score ' + str(self.clients[client_id].best_item['score']))
        log.msg('best id ' + self.clients[client_id].best_item['record_id'])
        log.msg('best place ' + str(self.clients[client_id].best_item_place))

        self.send_data_and_close_connection(client_id)


    def send_data_and_close_connection(self, client_id):
        result = {}
        result['top'] = self.clients[client_id].top
        result['place'] = self.clients[client_id].best_item_place

        j = json.dumps(result)
        c = self.crypt.crypt(j)

        self.clients[client_id].writeData(c)
        self.clients[client_id].transport.loseConnection()
        del self.clients[client_id]

    def _on_db_init_error(self, value):
        """
            DB initialization errorback.
        """
        log.msg('DB init errorback. Something went wrong in DB')

    def _on_db_error(self, value, client_id):
        """
            Errorback for client interaction with DB.
        """
        log.msg('DB errorback. Something went wrong in DB: ' + str(value))
        self.clients[client_id].writeData('4')
        self.clients[client_id].transport.loseConnection()

    def decodeUserRecords(self, data):
        log.msg('decodeUserRecords')
        return self.crypt.decrypt(data)
Exemple #24
0
	def __init__(self, job, db):
		self.job = job
		self.db = db
		
		self.archive = Archive()
		self.crypt = Crypt()
Exemple #25
0
class Backup:
	"""Handles complete backup flow. Check if file exists orhas been modified.
	Compresses, encrypts and uploads the file to th destination."""

	db = None
	job = None
	compress = None
	encrypt = None
	
	def __init__(self, job, db):
		self.job = job
		self.db = db
		
		self.archive = Archive()
		self.crypt = Crypt()
	
	def backup(self):
		"""Start backup process."""
		
		if not isdir(self.job['path']):
			self._list_files(
				None, dirname(self.job['path']), [basename(self.job['path']), ]
			)
		else:
			walk(self.job['path'], self._list_files, None)
		
	def _list_files(self, dir, basepath, files):
		"""Callback for walker. Iterates over filelist, builds absolute path
		and checks wheather to skip or upload the file."""
		
		for file in files:
			# absolute path
			path = join(basepath, file)
			
			# only work on files
			if isfile(path)	or (
				not isdir(path) and self.job.has_key('pre_command')):
				
				item = self.db.get_file(self.job['name'], path)
				
				# file is not in db
				if not item:
					self._backup_file(path)
				else:
					# file exists in db, but has a different mtime
					if isfile(path):
						mtime = getmtime(path)
						
						if int(item['mtime']) != int(mtime):
							self._backup_file(path)
					else:
						self._backup_file(path)
						
	def _execute_command(self, command):
		"""Execute pre- or postcommand."""
		if self.job.has_key(command):
			try:
				logging.info('[%s] Executing %s' 
					% (self.job['name'], self.job[command]))
				system(self.job[command])
			except:
				logging.warn('[%s] Command failed %s' 
					% (self.job['name'], self.job[command]))

	def _backup_file(self, path):
		"""Back ups specific file to desired storage device."""
		
		print('[%s] Starting backup for %s' % (self.job['name'], path))
		
		# precommand
		self._execute_command('pre_command')
		
		# get size, mtime
		file_info = self._file_info(path)
		
		# get storeage wrapper
		storage = self._get_account(self.job['destination'])
		dest = join(tempfile.gettempdir(), 'umaticssync')
		
		# is compression deired? bzip2 file
		if self.job.has_key('compress') and self.job['compress'] == 'true':
			logging.info('[%s] Compressing %s' % (self.job['name'], path))
			self.archive.compress(path, dest)
			old_dest = dest
			compressed = 1
		
		# is encryption desired? encrypt with user id
		if self.job.has_key('encrypt') and self.job['encrypt']:
			logging.info('[%s] Encrypting %s' % (self.job['name'], path))
			self.crypt.encrypt(self.job['encrypt'], dest)
			dest = dest + '.gpg'
			remove(old_dest)
			encrypted = 1
		
		# add file/increase revision
		info = self.db.add_file(
			self.job['name'], path, file_info['mtime'], file_info['size'], 
			encrypted, compressed)
		
		# build key and upload, cleanup
		key = normpath('%s/%s.r%%s' % (self.job['name'], path))
		logging.info('[%s] Uploading %s.r%s' 
			% (self.job['name'], path, info['revision']))
		storage.store_file(key % info['revision'], dest)
		remove(dest)
		
		# cleanup old revisions
		revision = int(info['revision']) - int(self.job['revisions'])
		if revision >= 0:
			print "del", key % revision
			storage.del_file(key % revision)
			
		# postcommand
		self._execute_command('post_command')
		
	def _file_info(self, path):
		"""Returns size and mtime."""
		return {'size': getsize(path), 'mtime': getmtime(path)}
		
	def _get_account(self, uri):
		"""Return storage engine object based on the provided URI string."""
		uri = urlsplit(uri)
		
		# s3 backend
		if uri[0] == 's3':
			a_key, s_key = uri[2][2:].split('@')[0].split(':')
			bucket = uri[2][2:].split('@')[1]
			
			from wrapper.S3Wrapper import S3Wrapper
			return S3Wrapper(a_key, s_key, bucket)
		# ftp server
		elif uri[0] == 'ftp':
			user, passwd = uri[2][2:].split('@')[0].split(':')
			host = uri[2][2:].split('@')[1]
			path = uri[2]
			
			from wrapper.FTPWrapper import FTPWrapper
			return FTPWrapper(host, user, passwd, path)
		# @todo: implement
		elif uri[0] == 'scp':
			pass
		# local storage backend
		elif uri[0] == 'file':
			path = uri[1]
			
			from wrapper.FileWrapper import FileWrapper
			return FileWrapper(path)

	def restore(self, revision):
		files = self.db.get_files(self.job['name'])
		
		if len(files) == 0:
			#logging.info('[%s] No files found for backup job')
			return False
		
		# get storage instance
		storage = self._get_account(self.job['destination'])
		
		# iterate thur files
		for file in files:
			try:
				# is given revision in allowed range?
				rev_diff = int(file['revision']) - int(self.job['revisions'])
				if int(revision) in range(rev_diff, file['revision'] + 1):
					rev = revision
				else:
					# fallback to latest file revision
					rev = file['revision']
			except:
				rev = file['revision']
			
			logging.info('[%s] Restoring %s.r%s' 
				% (self.job['name'], file['path'], rev))
			
			# get file
			key = normpath('%s/%s.r%s' % (self.job['name'], file['path'], rev))
			dest = join(tempfile.gettempdir(), 'umaticssync')
			
			logging.info('[%s] Downloading %s' 
				% (self.job['name'], file['path']))
			storage.get_file(key, dest)
			
			if file['encrypted'] == 1:
				logging.info('[%s] Decrypting %s' 
					% (self.job['name'], file['path']))
				self.crypt.decrypt(self.job['encrypt'], dest, dest)
			
			if file['compressed'] == 1:
				logging.info('[%S] Extracting %s' 
					% (self.job['name'], file['path']))
				self.archive.extract(dest)
			else:
				rename(dest, file['path'])
Exemple #26
0
    def __init__(self,
                 config,
                 mongo,
                 block_height,
                 bulletin_secret='',
                 username='',
                 value=0,
                 fee=0.0,
                 requester_rid='',
                 requested_rid='',
                 public_key='',
                 dh_public_key='',
                 private_key='',
                 dh_private_key='',
                 to='',
                 inputs='',
                 outputs='',
                 coinbase=False,
                 chattext=None,
                 signin=None):
        self.config = config
        self.mongo = mongo
        self.block_height = block_height
        self.bulletin_secret = bulletin_secret
        self.username = username
        self.requester_rid = requester_rid
        self.requested_rid = requested_rid
        self.public_key = public_key
        self.dh_public_key = dh_public_key
        self.private_key = private_key
        self.value = value
        self.fee = float(fee)
        self.dh_private_key = dh_private_key
        self.to = to
        self.time = str(int(time.time()))
        self.outputs = []
        for x in outputs:
            self.outputs.append(Output.from_dict(x))
        self.inputs = []
        for x in inputs:
            if 'signature' in x:
                self.inputs.append(
                    ExternalInput.from_dict(self.config, self.mongo, x))
            else:
                self.inputs.append(Input.from_dict(x))
        self.coinbase = coinbase
        self.chattext = chattext
        self.signin = signin
        self.do_money()
        inputs_concat = self.get_input_hashes()
        outputs_concat = self.get_output_hashes()
        if bulletin_secret:
            self.rid = self.generate_rid()
            if self.chattext:
                self.relationship = json.dumps({"chatText": self.chattext})
                self.cipher = Crypt(self.config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship)
            elif self.signin:
                for shared_secret in TU.get_shared_secrets_by_rid(
                        self.config, self.mongo, self.rid):
                    self.relationship = SignIn(self.signin)
                    self.cipher = Crypt(shared_secret.encode('hex'),
                                        shared=True)
                    self.encrypted_relationship = self.cipher.shared_encrypt(
                        self.relationship.to_json())
            else:
                if not self.dh_public_key or not self.dh_private_key:
                    a = os.urandom(32)
                    self.dh_public_key = scalarmult_base(a).encode('hex')
                    self.dh_private_key = a.encode('hex')
                self.relationship = self.generate_relationship()
                if not private_key:
                    raise BaseException('missing private key')
                self.cipher = Crypt(self.config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship.to_json())
        else:
            self.rid = ''
            self.encrypted_relationship = ''

        self.header = (self.public_key + self.time + self.dh_public_key +
                       self.rid + self.encrypted_relationship +
                       "{0:.8f}".format(self.fee) + self.requester_rid +
                       self.requested_rid + inputs_concat + outputs_concat)
        self.hash = hashlib.sha256(self.header).digest().encode('hex')
        if self.private_key:
            self.transaction_signature = TU.generate_signature_with_private_key(
                private_key, self.hash)
        else:
            self.transaction_signature = ''
        self.transaction = self.generate_transaction()
Exemple #27
0
class TransactionFactory(object):
    def __init__(self,
                 config,
                 mongo,
                 block_height,
                 bulletin_secret='',
                 username='',
                 value=0,
                 fee=0.0,
                 requester_rid='',
                 requested_rid='',
                 public_key='',
                 dh_public_key='',
                 private_key='',
                 dh_private_key='',
                 to='',
                 inputs='',
                 outputs='',
                 coinbase=False,
                 chattext=None,
                 signin=None):
        self.config = config
        self.mongo = mongo
        self.block_height = block_height
        self.bulletin_secret = bulletin_secret
        self.username = username
        self.requester_rid = requester_rid
        self.requested_rid = requested_rid
        self.public_key = public_key
        self.dh_public_key = dh_public_key
        self.private_key = private_key
        self.value = value
        self.fee = float(fee)
        self.dh_private_key = dh_private_key
        self.to = to
        self.time = str(int(time.time()))
        self.outputs = []
        for x in outputs:
            self.outputs.append(Output.from_dict(x))
        self.inputs = []
        for x in inputs:
            if 'signature' in x:
                self.inputs.append(
                    ExternalInput.from_dict(self.config, self.mongo, x))
            else:
                self.inputs.append(Input.from_dict(x))
        self.coinbase = coinbase
        self.chattext = chattext
        self.signin = signin
        self.do_money()
        inputs_concat = self.get_input_hashes()
        outputs_concat = self.get_output_hashes()
        if bulletin_secret:
            self.rid = self.generate_rid()
            if self.chattext:
                self.relationship = json.dumps({"chatText": self.chattext})
                self.cipher = Crypt(self.config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship)
            elif self.signin:
                for shared_secret in TU.get_shared_secrets_by_rid(
                        self.config, self.mongo, self.rid):
                    self.relationship = SignIn(self.signin)
                    self.cipher = Crypt(shared_secret.encode('hex'),
                                        shared=True)
                    self.encrypted_relationship = self.cipher.shared_encrypt(
                        self.relationship.to_json())
            else:
                if not self.dh_public_key or not self.dh_private_key:
                    a = os.urandom(32)
                    self.dh_public_key = scalarmult_base(a).encode('hex')
                    self.dh_private_key = a.encode('hex')
                self.relationship = self.generate_relationship()
                if not private_key:
                    raise BaseException('missing private key')
                self.cipher = Crypt(self.config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship.to_json())
        else:
            self.rid = ''
            self.encrypted_relationship = ''

        self.header = (self.public_key + self.time + self.dh_public_key +
                       self.rid + self.encrypted_relationship +
                       "{0:.8f}".format(self.fee) + self.requester_rid +
                       self.requested_rid + inputs_concat + outputs_concat)
        self.hash = hashlib.sha256(self.header).digest().encode('hex')
        if self.private_key:
            self.transaction_signature = TU.generate_signature_with_private_key(
                private_key, self.hash)
        else:
            self.transaction_signature = ''
        self.transaction = self.generate_transaction()

    def do_money(self):
        my_address = str(
            P2PKHBitcoinAddress.from_pubkey(self.public_key.decode('hex')))
        input_txns = BU.get_wallet_unspent_transactions(
            self.config, self.mongo, my_address)
        miner_transactions = self.mongo.db.miner_transactions.find()
        mtxn_ids = []
        for mtxn in miner_transactions:
            for mtxninput in mtxn['inputs']:
                mtxn_ids.append(mtxninput['id'])

        if self.inputs:
            inputs = self.inputs
        else:
            inputs = []
            for input_txn in input_txns:
                if input_txn['id'] not in mtxn_ids:
                    if 'signature' in input_txn:
                        inputs.append(
                            ExternalInput.from_dict(self.config, self.mongo,
                                                    input_txn))
                    else:
                        inputs.append(Input.from_dict(input_txn))

        input_sum = 0
        if self.coinbase:
            self.inputs = []
        else:
            if inputs:
                needed_inputs = []
                done = False
                for y in inputs:
                    print y.id
                    txn = BU.get_transaction_by_id(self.config,
                                                   self.mongo,
                                                   y.id,
                                                   instance=True)
                    if isinstance(y, ExternalInput):
                        y.verify()
                        address = str(
                            P2PKHBitcoinAddress.from_pubkey(
                                txn.public_key.decode('hex')))
                    else:
                        address = my_address
                    for txn_output in txn.outputs:
                        if txn_output.to == address:
                            input_sum += txn_output.value
                            needed_inputs.append(y)
                            if input_sum >= (
                                    sum([x.value
                                         for x in self.outputs]) + self.fee):
                                done = True
                                break
                    if done == True:
                        break

                if not done:
                    raise NotEnoughMoneyException('not enough money')
                self.inputs = needed_inputs
            else:
                self.inputs = []

            remainder = input_sum - (sum([x.value
                                          for x in self.outputs]) + self.fee)

            found = False
            for x in self.outputs:
                if my_address == x.to:
                    found = True
                    x.value += remainder
            if not found:
                return_change_output = Output(to=my_address, value=remainder)
                self.outputs.append(return_change_output)

    def get_input_hashes(self):
        from fastgraph import FastGraph
        input_hashes = []
        for x in self.inputs:
            txn = BU.get_transaction_by_id(self.config,
                                           self.mongo,
                                           x.id,
                                           instance=True,
                                           include_fastgraph=isinstance(
                                               self, FastGraph))
            input_hashes.append(str(txn.transaction_signature))

        return ''.join(sorted(input_hashes, key=str.lower))

    def get_output_hashes(self):
        outputs_sorted = sorted([x.to_dict() for x in self.outputs],
                                key=lambda x: x['to'].lower())
        return ''.join(
            [x['to'] + "{0:.8f}".format(x['value']) for x in outputs_sorted])

    def generate_rid(self):
        my_bulletin_secret = self.config.get_bulletin_secret()
        if my_bulletin_secret == self.bulletin_secret:
            raise BaseException(
                'bulletin secrets are identical. do you love yourself so much that you want a relationship on the blockchain?'
            )
        bulletin_secrets = sorted(
            [str(my_bulletin_secret),
             str(self.bulletin_secret)],
            key=str.lower)
        return hashlib.sha256(
            str(bulletin_secrets[0]) +
            str(bulletin_secrets[1])).digest().encode('hex')

    def generate_relationship(self):
        return Relationship(
            dh_private_key=self.dh_private_key,
            their_bulletin_secret=self.bulletin_secret,
            their_username=self.username,
            my_bulletin_secret=self.config.get_bulletin_secret(),
            my_username=self.config.username)

    def generate_transaction(self):
        return Transaction(self.config,
                           self.mongo,
                           self.block_height,
                           self.time,
                           self.rid,
                           self.transaction_signature,
                           self.encrypted_relationship,
                           self.public_key,
                           self.dh_public_key,
                           float(self.fee),
                           self.requester_rid,
                           self.requested_rid,
                           self.hash,
                           inputs=[x.to_dict() for x in self.inputs],
                           outputs=[x.to_dict() for x in self.outputs],
                           coinbase=self.coinbase)

    def generate_transaction_signature(self):
        return TU.generate_signature(self.hash, self.private_key)
    def __init__(self,
                 bulletin_secret='',
                 username='',
                 value=0,
                 fee=0.0,
                 requester_rid='',
                 requested_rid='',
                 public_key='',
                 dh_public_key='',
                 private_key='',
                 dh_private_key='',
                 to='',
                 inputs='',
                 outputs='',
                 coinbase=False,
                 chattext=None,
                 signin=None):
        self.bulletin_secret = bulletin_secret
        self.username = username
        self.requester_rid = requester_rid
        self.requested_rid = requested_rid
        self.public_key = public_key
        self.dh_public_key = dh_public_key
        self.private_key = private_key
        self.value = value
        self.fee = float(fee)
        self.dh_private_key = dh_private_key
        self.to = to
        self.outputs = outputs or []
        self.inputs = inputs
        self.coinbase = coinbase
        self.chattext = chattext
        self.signin = signin
        self.do_money()
        inputs_concat = self.get_input_hashes()
        outputs_concat = self.get_output_hashes()
        if bulletin_secret:
            self.rid = self.generate_rid()
            if self.chattext:
                self.relationship = json.dumps({"chatText": self.chattext})
            elif self.signin:
                for shared_secret in TU.get_shared_secrets_by_rid(self.rid):
                    self.relationship = SignIn(self.signin)
                    self.cipher = Crypt(shared_secret.encode('hex'),
                                        shared=True)
                    self.encrypted_relationship = self.cipher.shared_encrypt(
                        self.relationship.to_json())
            else:
                self.relationship = self.generate_relationship()
                if not private_key:
                    raise BaseException('missing private key')
                self.cipher = Crypt(Config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship.to_json())
        else:
            self.rid = ''
            self.encrypted_relationship = ''
        self.hash = hashlib.sha256(self.dh_public_key + self.rid +
                                   self.encrypted_relationship +
                                   "{0:.8f}".format(self.fee) +
                                   self.requester_rid + self.requested_rid +
                                   inputs_concat +
                                   outputs_concat).digest().encode('hex')

        self.transaction_signature = self.generate_transaction_signature()
        self.transaction = self.generate_transaction()
Exemple #29
0
from crypt import Crypt

c = Crypt()
a = c.encrypt('12345')
print(a)
b = c.decrypt(a)
print(b)
Exemple #30
0
    sock.setblocking(0)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)

    # Create a new IP packet and set its source and destination addresses
    ip = ImpactPacket.IP()

    # Create a new ICMP packet of type ECHO REPLY
    icmp = ImpactPacket.ICMP()
    icmp.set_icmp_type(icmp.ICMP_ECHOREPLY)

    # Instantiate an IP packets decoder
    decoder = ImpactDecoder.IPDecoder()

    # encrypt packet
    encryptor = Crypt(PASSWORD)

    #
    server = client = None
    while True:
        reply = ''
        # Wait for incoming replies
        if sock in select.select([sock], [], [])[0]:
            buf = sock.recv(4096)

            if not len(buf):
                # Socket remotely closed
                sock.close()
                sys.exit(0)

            # Packet received; decode and display it
Exemple #31
0
# coding: utf-8

#import tanarky_crypt
from crypt import Crypt

a = "foo"
c = Crypt()


 def test_decrypt(self):
     c = Crypt(self.cipher_key)
     decrypted = c.decrypt('3b1b943Dcrqm179NGt3GnA==')
     assert decrypted == 'ace to the base'
Exemple #33
0
 def __init__(self):
     from crypt import Crypt
     self.configFile = os.path.expanduser("~/.yatc/yatc.conf")
     self.config = {}
     self.crypt = Crypt()
     logging.info("Config initialized.")
Exemple #34
0
    end = text.index('l') + 1
    atol = Crypt.shift(text, shift1)
    atol = atol[:end]

    # shift M-Z
    start = text.index('m')
    mtoz = Crypt.shift(text, shift2)
    mtoz = mtoz[start:]

    domain = atol + mtoz
    return domain


cipher = "DTZBTSYEHOLHAHYKHALHB".lower()
domain = "abcdefghijklmnopqrstuvwxyz"
otherDomain = specialshift(domain, 3, 5)
print domain
print otherDomain


def getDomain(text):
    return domain


c = Crypt()
cipher = c.mcrypt(plain, mapFactory=specialshift, mapFactoryArgs=(3, 5))
decipher = c.mcrypt(cipher, domain=otherDomain, mapFactory=getDomain)

print cipher
print decipher
Exemple #35
0
class Api:
    """ Deal with API requests and local clipboard
    """

    SERVER = None
    USER = None
    HASH_LOGIN = None
    HASH_MSG = None
    crypto = None

    def __init__(self, server, user, hash_login, hash_msg):
        self.SERVER = server
        self.USER = user
        self.HASH_LOGIN = hash_login
        self.HASH_MSG = hash_msg
        self.crypto = Crypt(username=user,
                            password=None,
                            hash_login=hash_login,
                            hash_msg=hash_msg)

    def upload(self):
        """
        Send the copied text to SERVER
        """
        clip = self.copy()
        clip_encrypted = self.crypto.encrypt(clip)
        payload = {"text": clip_encrypted, "device": f"{Config.DEVICE_ID}"}
        try:
            res = requests.post(
                self.SERVER + Config.API_COPY_PASTE,
                data=payload,
                auth=(self.USER, self.HASH_LOGIN),
                timeout=Config.CONN_TIMEOUT,
                verify=Config.VERIFY_SSL_CERT,
                headers=Config.HEADERS,
            )
        except requests.exceptions.RequestException as e:
            log.exception("Error in upload request")
            raise ApiException(e)
        else:
            if res.status_code == 201:
                log.info("Success! Copied to Cloud-Clipboard.")
                return clip
            else:
                log.error(f"Error cannot upload clip: {res.text}")
                raise ApiException(res.text[0:Config.MAX_RESPONSE_LEN])

    def download(self):
        """
        Download last or all clips from SERVER and updates the local clipboard
        """
        log.info("downloading clips")
        url = self.SERVER + Config.API_COPY_PASTE
        try:
            res = requests.get(
                url=url,
                auth=(self.USER, self.HASH_LOGIN),
                timeout=Config.CONN_TIMEOUT,
                verify=Config.VERIFY_SSL_CERT,
                headers=Config.HEADERS,
            )
        except requests.exceptions.RequestException as e:
            log.exception("Error in download request")
            raise ApiException(e)
        else:
            if res.status_code == 200:
                clips_decrypted = self.parse_and_decrypt_response(res)
                log.info(f"Got new clips from SERVER:\n{clips_decrypted}")
                self.paste(clips_decrypted[-1])
                return clips_decrypted
            else:
                log.error(
                    f"Cannot download clips: {res.status_code} - {res.text}")
                raise ApiException(res.text[0:Config.MAX_RESPONSE_LEN])

    def parse_and_decrypt_response(self, response):
        """ Parse list clip response and decrypt content
        Returns:
            List: Contains one or more clips. Ordered by creation date (DESC)
        """
        clips_decrypted = []
        try:
            clips = json.loads(response.text)
            for clip in clips:
                clips_decrypted.append(self.crypto.decrypt(clip["text"]))
            if len(clips) == 0:
                clips_decrypted = ["There are no shared Clips yet"]
        except Exception as e:
            log.e(f"Could not parse and decrypt: {e}")
            clips_decrypted = [""]
        return clips_decrypted

    @staticmethod
    def paste(data):
        """
        Copies 'data' to local clipboard which enables pasting.
        """
        pyperclip.copy(data)

    @staticmethod
    def copy():
        """
        Return the current clipboard text
        """
        data = pyperclip.paste()
        return data

    @staticmethod
    def register(server, user, pw):
        """
        register user on server using hash generated from pw
        """
        crypto = Crypt(user, pw)
        login_hash = crypto.pw_hash_login
        payload = {"username": user, "password": login_hash}
        try:
            res = requests.post(
                server + Config.API_REGISTER,
                data=payload,
                timeout=Config.CONN_TIMEOUT,
                verify=Config.VERIFY_SSL_CERT,
                headers=Config.HEADERS,
            )
        except requests.exceptions.RequestException as e:
            log.exception("Error in register request")
            raise RegisterException(e)
        if res.status_code == 201:
            log.info(f"Hi {user}! You are all set.")
            return True
        else:
            log.error(f"Cannot register user: {res.status_code} - {res.text}")
            raise RegisterException(res.text[0:Config.MAX_RESPONSE_LEN])

    @staticmethod
    def login(server, user, pw):
        """
        authenticate user using hash generated from pw
        """
        crypto = Crypt(user, pw)
        login_hash = crypto.pw_hash_login
        try:
            res = requests.get(
                server + Config.API_LOGIN,
                auth=(user, login_hash),
                timeout=Config.CONN_TIMEOUT,
                verify=Config.VERIFY_SSL_CERT,
                headers=Config.HEADERS,
            )
        except requests.exceptions.RequestException as e:
            log.exception("Error in login request")
            raise LoginException(e)
        if res.status_code >= 200 and res.status_code < 400:
            log.info("Login successful")
            return True
        else:
            log.error(f"Login failed: {res.status_code} - {res.text}")
            raise LoginException(res.text[0:Config.MAX_RESPONSE_LEN])
        # It is not the first time
        else:
        
            logging.debug('cam_pwd does NOT exist in config.txt - we add it')
             
            #Update the Cam Password via the cgi
            fname = 'http://'+config['cam_ip']+'/cgi-bin/pwdgrp_cgi?action=update&user=admin&pwd=admin&username=admin&password='******'Updating the cam_pwd on the camera side:' + fname)

         
        # Call to CGI
        urllib.urlopen(fname)
         
        # Encrypt the Cam Password to store it in the config file 
        try:
            c     = Crypt()
            value = c.encrypt(value)
            logging.debug('cam_pwd successfully encrypted') 
            
            # Write new pwd in config.txt
            line = "cam_pwd=" + str(value) + "\n"
            file.write(line)   
        except:
            logging.error('IMPOSSIBLE to encrypted the following cam_pwd ' + str(value))
            logging.debug('Config (ERROR) ' + str(config))
        
        del tmp_config['new_cam_pwd']


logging.debug('Updating config.txt') 
for key in tmp_config:
Exemple #37
0
from base64 import b64decode
from crypt import Crypt

p = b64decode('=i')
x = Crypt(p)

src = '/Users/nbari/.ftrunk/eb/c5/99/ebc5999af324a1f4272e15795690cb979dbea921a56fbd4957f5f83055bb7c04363d35bf475856637f0ff0929400507f1e998b7c709dae1de53748ab5f3381ca'

with open(src, 'rb') as in_file, open('/tmp/out.bz2', 'wb') as out_file:
    x.decrypt(in_file, out_file)
def get_assignments():

    print(ascii_art.return_ascii())

    print('Tentando encontrar o Bearer token...\n')

    c = Crypt()

    encrypted_token_file = open('token.txt', 'rb')
    encrypted_token = encrypted_token_file.read()
    encrypted_token_file.close()

    if not encrypted_token:
        print(
            f'{Fore.YELLOW}Não conseguimos localizar seu token salvo em cache, digite manualmente{Style.RESET_ALL}'
        )
        print('Digite o seu bearer token do Teams: ')
        bearer_token = str(input('')).strip()

        print('\n')
        print(Fore.YELLOW + '!' + Style.RESET_ALL)
        print(
            Fore.YELLOW +
            'Não se preocupe, não enviaremos essa informação para nenhum local, apenas será encriptada na sua máquina como cache.'
            + Style.RESET_ALL)
        print(Fore.YELLOW + '!' + Style.RESET_ALL)
        print('\n')

        key_file = open('key.key', 'rb')
        key = key_file.read()
        key_file.close()

        if not key:
            c.generate_new_key()
            c.encrypt(bearer_token)
        else:
            c.encrypt(bearer_token)

        encrypted_token_file = open('token.txt', 'rb')
        encrypted_token = encrypted_token_file.read()
        encrypted_token_file.close()

        if not encrypted_token:
            print(
                f'{Fore.RED}Ocorreu um erro, tente novamente{Style.RESET_ALL}')

        original_token = c.decrypt(encrypted_token)
    else:
        try:
            original_token = c.decrypt(encrypted_token)
        except Exception as err:
            print(f'{Fore.RED}{err}{Style.RESET_ALL}')
            clear_token()
            exit()

        print(
            f'{Fore.BLUE}Seu token foi encontrado em cache!{Style.RESET_ALL}\n'
        )

    print('Pegando assignments... (Isso pode demorar alguns minutos)\n')

    ts = TeamScrap(original_token)

    try:
        classes_assignments = ts.get_all_classes_assignments()
    except Exception as err:
        print(f'{Fore.RED}{err}{Style.RESET_ALL}\n')
        print(
            f'{Fore.RED}Verifique se o token não expirou ou está correto{Style.RESET_ALL}\n'
        )
        clear_token()
        exit()

    overdue_assignments = 0

    print('=' * 100)
    message = ""
    for class_assignment in classes_assignments:
        created_date_time = class_assignment['assignmentInfo'][
            'createdDateTime']
        [created_date_parsed,
         created_hours_parsed] = parse_teams_date_time(created_date_time)
        created_date_final = datetime(year=int(created_date_parsed[0]),
                                      month=int(created_date_parsed[1]),
                                      day=int(created_date_parsed[2]))
        bimester_init_date = datetime(year=int(2021), month=int(2), day=int(1))

        if created_date_final > bimester_init_date:
            due_date_time = class_assignment['assignmentInfo']['dueDateTime']
            [date_parsed, hours_parsed] = parse_teams_date_time(due_date_time)

            date_init = datetime.now()
            date_final = datetime(year=int(date_parsed[0]),
                                  month=int(date_parsed[1]),
                                  day=int(date_parsed[2]),
                                  hour=int(hours_parsed[0]),
                                  minute=int(hours_parsed[1]),
                                  second=int(hours_parsed[2]))

            date_final -= timedelta(hours=3)

            [final_date_parsed,
             final_hours_parsed] = parse_date_time(date_final)

            remaining_date = date_final - date_init

            remaining_date_parsed = str(remaining_date).split(',')

            message += f"""\n\n📝 Tarefa: {class_assignment['assignmentInfo']['displayName']}
						\n📚 Disciplina: {class_assignment["classInfo"][0]["name"]}
						\n⏳ Data de entrega: {final_date_parsed[2]}/{final_date_parsed[1]}/{final_date_parsed[0]}
						às {final_hours_parsed[0]}:{final_hours_parsed[1]}:{final_hours_parsed[2]}"""

            if class_assignment['assignmentInfo'][
                    'allowLateSubmissions'] == 'true':
                message += "\n⏰ Aceita atrasos: ✅SIM✅"
            else:
                message += "\n⏰ Aceita atrasos: ❌NÃO❌"

            if len(remaining_date_parsed) > 1:
                remaining_days = int(
                    remaining_date_parsed[0].strip().split(' ')[0])
                remaining_hours = remaining_date_parsed[1].strip().split(':')
            else:
                remaining_hours = remaining_date_parsed[0].strip().split(':')

            if int(remaining_days) < 0:
                message += "\n⚙️ Status: ⌛️VENCIDA⌛️"
            else:
                message += "\n⚙️ Status: 🏃CORRE QUE DÁ TEMPO🏃"

            message += "\n" + "=" * 10
        else:
            pass

    return message
 def test_encrypt(self):
     c = Crypt(self.cipher_key)
     encrypted = c.encrypt('some random plain text')
     assert encrypted == 'b1XdLeAJ54bz/ALcDd2FeAez7y5z33Le'
Exemple #40
0
 def __init__(self, name, host = 'localhost', port = 10000):
     Client.__init__(self, host, port)
     self.name = name
     self.crypt = Crypt()
     self.handlers = [self.socket, sys.stdin]
Exemple #41
0
def encout(filename, data):
    with open(filename, 'w') as outfile:
        outfile.write(data)


def decin(filename):
    data = open(filename).read()
    return data


####################################################################################################
## file read
####################################################################################################
fileobj = open(sys.argv[1])
msg = bytes(fileobj.read(), "utf-8")
####################################################################################################

ccc = Crypt()
key = bytes(sys.argv[1], "utf-8")

#encrypted = ccc.encrypt(key, msg)
#decrypted = ccc.decrypt(key, encrypted)

#encout('enc_' + sys.argv[1], encrypted)
fileenc = decin('enc_test')
decrypted = ccc.decrypt(key, fileenc)

#print(encrypted)
print(decrypted)
class TransactionFactory(object):
    def __init__(self,
                 bulletin_secret='',
                 username='',
                 value=0,
                 fee=0.0,
                 requester_rid='',
                 requested_rid='',
                 public_key='',
                 dh_public_key='',
                 private_key='',
                 dh_private_key='',
                 to='',
                 inputs='',
                 outputs='',
                 coinbase=False,
                 chattext=None,
                 signin=None):
        self.bulletin_secret = bulletin_secret
        self.username = username
        self.requester_rid = requester_rid
        self.requested_rid = requested_rid
        self.public_key = public_key
        self.dh_public_key = dh_public_key
        self.private_key = private_key
        self.value = value
        self.fee = float(fee)
        self.dh_private_key = dh_private_key
        self.to = to
        self.outputs = outputs or []
        self.inputs = inputs
        self.coinbase = coinbase
        self.chattext = chattext
        self.signin = signin
        self.do_money()
        inputs_concat = self.get_input_hashes()
        outputs_concat = self.get_output_hashes()
        if bulletin_secret:
            self.rid = self.generate_rid()
            if self.chattext:
                self.relationship = json.dumps({"chatText": self.chattext})
            elif self.signin:
                for shared_secret in TU.get_shared_secrets_by_rid(self.rid):
                    self.relationship = SignIn(self.signin)
                    self.cipher = Crypt(shared_secret.encode('hex'),
                                        shared=True)
                    self.encrypted_relationship = self.cipher.shared_encrypt(
                        self.relationship.to_json())
            else:
                self.relationship = self.generate_relationship()
                if not private_key:
                    raise BaseException('missing private key')
                self.cipher = Crypt(Config.wif)
                self.encrypted_relationship = self.cipher.encrypt(
                    self.relationship.to_json())
        else:
            self.rid = ''
            self.encrypted_relationship = ''
        self.hash = hashlib.sha256(self.dh_public_key + self.rid +
                                   self.encrypted_relationship +
                                   "{0:.8f}".format(self.fee) +
                                   self.requester_rid + self.requested_rid +
                                   inputs_concat +
                                   outputs_concat).digest().encode('hex')

        self.transaction_signature = self.generate_transaction_signature()
        self.transaction = self.generate_transaction()

    def do_money(self):
        Mongo.init()
        my_address = str(
            P2PKHBitcoinAddress.from_pubkey(self.public_key.decode('hex')))
        input_txns = BU.get_wallet_unspent_transactions(my_address)
        miner_transactions = Mongo.db.miner_transactions.find()
        mtxn_ids = []
        for mtxn in miner_transactions:
            for mtxninput in mtxn['inputs']:
                mtxn_ids.append(mtxninput['id'])

        inputs = [
            Input.from_dict(input_txn) for input_txn in input_txns
            if input_txn['id'] not in mtxn_ids
        ]

        input_sum = 0
        if self.coinbase:
            self.inputs = []
        else:
            needed_inputs = []
            done = False
            for y in inputs:
                print y.id
                txn = BU.get_transaction_by_id(y.id, instance=True)
                for txn_output in txn.outputs:
                    if txn_output.to == my_address:
                        input_sum += txn_output.value
                        needed_inputs.append(y)
                        if input_sum >= (sum([x.value for x in self.outputs]) +
                                         self.fee):
                            done = True
                            break
                if done == True:
                    break

            if not done:
                raise NotEnoughMoneyException('not enough money')
            self.inputs = needed_inputs

            return_change_output = Output(
                to=my_address,
                value=input_sum - (sum([x.value
                                        for x in self.outputs]) + self.fee))
            self.outputs.append(return_change_output)

    def get_input_hashes(self):
        input_hashes = []
        for x in self.inputs:
            txn = BU.get_transaction_by_id(x.id, instance=True)
            input_hashes.append(str(txn.transaction_signature))

        return ''.join(sorted(input_hashes, key=str.lower))

    def get_output_hashes(self):
        outputs_sorted = sorted([x.to_dict() for x in self.outputs],
                                key=lambda x: x['to'].lower())
        return ''.join(
            [x['to'] + "{0:.8f}".format(x['value']) for x in outputs_sorted])

    def generate_rid(self):
        my_bulletin_secret = Config.get_bulletin_secret()
        if my_bulletin_secret == self.bulletin_secret:
            raise BaseException(
                'bulletin secrets are identical. do you love yourself so much that you want a relationship on the blockchain?'
            )
        bulletin_secrets = sorted(
            [str(my_bulletin_secret),
             str(self.bulletin_secret)],
            key=str.lower)
        return hashlib.sha256(
            str(bulletin_secrets[0]) +
            str(bulletin_secrets[1])).digest().encode('hex')

    def generate_relationship(self):
        return Relationship(dh_private_key=self.dh_private_key,
                            their_bulletin_secret=self.bulletin_secret,
                            their_username=self.username,
                            my_bulletin_secret=Config.get_bulletin_secret(),
                            my_username=Config.username)

    def generate_transaction(self):
        return Transaction(self.rid,
                           self.transaction_signature,
                           self.encrypted_relationship,
                           self.public_key,
                           self.dh_public_key,
                           float(self.fee),
                           self.requester_rid,
                           self.requested_rid,
                           self.hash,
                           inputs=self.inputs,
                           outputs=self.outputs,
                           coinbase=self.coinbase)

    def generate_transaction_signature(self):
        return TU.generate_signature(self.hash)
Exemple #43
0
    return [date_parsed, hour_parsed]


def parse_date_time(date_time):
    all_date_parsed = str(date_time).split(' ')
    date_parsed = all_date_parsed[0].split('-')
    hour_parsed = all_date_parsed[1].split(':')

    return [date_parsed, hour_parsed]


print(ascii_art.return_ascii())

print('Tentando encontrar o Bearer token...\n')

c = Crypt()

encrypted_token_file = open('token.txt', 'rb')
encrypted_token = encrypted_token_file.read()
encrypted_token_file.close()

if not encrypted_token:
    print(
        f'{Fore.YELLOW}Não conseguimos localizar seu token salvo em cache, digite manualmente{Style.RESET_ALL}'
    )
    print('Digite o seu bearer token do Teams: (? para ajuda)')
    bearer_token = str(input('')).strip()

    if bearer_token == '?':
        tutorial()
def get_clear_password(host, user, password):
    key = host + user
    s1 = sha1()
    s1.update(key.encode())
    key = s1.digest()
    return Crypt.decrypt(password, key[:16])