Exemple #1
0
def main():
	generated_key = key_exchange()
	key = format_key(generated_key)
	enc_pass = encrypt(password, key)
	send(enc_pass)
	enc = read()
	flag = decrypt(enc, key)
Exemple #2
0
    def response(self, TGT_ID, authenticator_encrypted, addr):
        TGT, service_id = literal_eval(TGT_ID)
        # Unencrypted TGT and service id come as string'd double

        TGT_decrypted = lib.decrypt_tuple(TGT, self.private_key)
        TGT_username, TGT_addr, expiration, TGS_session_key = TGT_decrypted
        # Unpack TGT

        username, time = lib.decrypt_tuple(authenticator_encrypted,
                                           TGS_session_key)
        # Encrypted username and time.

        assert username == TGT_username
        assert addr == TGT_addr
        # Make sure they are who they say they are. I think we could omit this.

        SS_session_key = str(uuid.uuid1())
        # Session key for the service server

        CTS = (username, addr, expiration, SS_session_key)
        service_server_key = db.retrieve_server(service_id)
        CTS_encrypted = lib.encrypt_tuple(CTS, service_server_key)
        # Client-to-server ticket

        SS_session_key_encrypted = lib.encrypt(SS_session_key, TGS_session_key)
        return (CTS_encrypted, SS_session_key_encrypted)
Exemple #3
0
    def service_request(self, CTS, CTS_key, url):
        authenticator = (self.user, str(time()))
        authenticator_encrypted = lib.encrypt(str(authenticator), CTS_key)

        timestamp_encrypted = send((CTS, authenticator_encrypted),
                                   url).split()[0]
        timestamp = lib.decrypt(timestamp_encrypted, CTS_key)

        return timestamp == authenticator[1]
def main():
    generated_key = key_exchange()
    key = format_key(generated_key)
    enc_pass = read()
    dec_pass = decrypt(enc_pass, key)
    if dec_pass != password:
        print("wrong password, terminating")
        return
    enc = encrypt(flag, key)
    send(enc)
    def response(self, CTS_encrypted, authenticator_encrypted, addr):
        CTS = lib.decrypt_tuple(CTS_encrypted, self.private_key)
        username, CTS_addr, expiration, SS_session_key = CTS
        # unpack client-to-server ticket

        ID, timestamp = lib.decrypt_tuple(authenticator_encrypted, SS_session_key)
        # unpack authenticator

        confirmation = lib.encrypt(timestamp, SS_session_key)
        # send the user's timestamp back to them as a confirmation of login

        return (confirmation, )
    def response(self, username, _, addr):
        secret = db.retrieve_user(username)
        TGS_session_key = str(uuid.uuid1())

        TGS_encrypted = lib.encrypt(TGS_session_key, secret)

        expiration = time() + TIMEOUT
        TGT = (username, addr, expiration, TGS_session_key)
        TGS_server_key = db.retrieve_server(db.TGS_NAME)
        TGT_encrypted = lib.encrypt_tuple(TGT, TGS_server_key)

        return (TGS_encrypted, TGT_encrypted)
Exemple #7
0
    def response(self, CTS_encrypted, authenticator_encrypted, addr):
        CTS = lib.decrypt_tuple(CTS_encrypted, self.private_key)
        username, CTS_addr, expiration, SS_session_key = CTS
        # unpack client-to-server ticket

        ID, timestamp = lib.decrypt_tuple(authenticator_encrypted, SS_session_key)
        # unpack authenticator

        confirmation = lib.encrypt('0', SS_session_key)
        # send faulty timestamp

        return (confirmation, )
Exemple #8
0
def engine(args):
    try:
        if args.Encrypt is True:
            if args.Decrypt is True:
                parser.error(
                    'Cannot use --Encrypt and --Decrypt given together.')
                sys.exit(1)
            else:
                pass
        if args.Encrypt is False:
            if args.Decrypt is False:
                parser.error(
                    'Must use either --Encrypt, or --Decrypt modes. Not both.')
                sys.exit(1)
            else:
                pass
        if not args.File:
            parser.error(
                'Cannot use --Encrypt, or --Decrypt without a file location.')
            sys.exit(1)
        if not args.Password:
            parser.error(
                'Cannot use --Encrypt, or --Decrypt without a password.')
            sys.exit(1)
        if not args.IV:
            parser.error('Cannot use --Encrypt, or --Decrypt without an IV.')
            sys.exit(1)
        key = padpwd(args.Password)
        iv = padiv(args.IV)
        settings = opts(key, iv)
        op = reader(args.File)
        if args.Encrypt is True:
            pd = pad(op)
            enc = encrypt(pd)
            wr = writer(args.File, enc)
            print('Encryption completed for: {}'.format(args.File))
            sys.exit(0)
        if args.Decrypt is True:
            dec = decrypt(op)
            unp = unpad(dec)
            wr = writer(args.File, unp)
            print('Decryption completed for: {}'.format(args.File))
            sys.exit(0)
        else:
            sys.exit(0)
    except KeyboardInterrupt:
        sys.exit(1)
    except FileNotFoundError:
        print('File Not Found: {}'.format(args.File))
        sys.exit(1)
Exemple #9
0
class MainPage(webapp2.RequestHandler):
    def get(self):
        text = '''<p>This version of keepagent server use <strong>%s</strong> protocol.</p>
        <p>请检查您的客户端是否使用了同一协议。</p>''' % lib.protocol

        self.response.headers['Content-Type'] = 'text/html; charset=UTF-8'
        self.response.write(text)

    def post(self):
        #记录一个是否加密的状态变量
        is_crypted = int(self.request.body[0])

        req_body = lib.decrypt(self.request.body)
        req_body = lib.loadDict(req_body)

        method = getattr(urlfetch, req_body.command)

        # 如超时则自动重试4次,4次失败后,GAE会抛错并返回给client 500错误。
        for dl in lib.deadlineRetry:
            try:
                res = urlfetch.fetch(
                    url=req_body.path,
                    payload=lib.atob(req_body.payload),
                    method=method,
                    headers=json.loads(req_body.headers),
                    follow_redirects=False,
                    deadline=dl,
                    validate_certificate=True,
                )
            except urlfetch.DownloadError, e:
                logging.error(u'下载错误: %s' % e)
            else:
                break  #没有抛出任何异常则跳出循环

        result = {
            'status_code': res.status_code,  # int
            # TODO: If there are multiple headers with the same name, their values will be joined into a single comma-separated string. If the values already contained commas (for example, Set-Cookie headers), you may want to use header_msg.get_headers(header_name) to retrieve a list of values instead.
            'headers': json.dumps(dict(res.headers)),
            'content': lib.btoa(res.content),  # str
        }

        result = lib.dumpDict(result)

        if is_crypted:
            result = lib.encrypt(result)
        else:
            result = '0' + result

        self.response.write(result)
Exemple #10
0
    def encrypt_request_payload(self, payload):
        assert self.ecdh_server_public_key

        encrypted = encrypt(self.request_encryption_key, payload)
        hmac = hmac_sha256(self.request_hmac_key, self.public_key + encrypted)
        return encrypted, hmac
Exemple #11
0
    def do_GET(self):

        # headers is a dict-like object, it doesn't have `iteritems` method, so convert it to `dict`
        req_headers = dict(self.headers)  # dict
        req_headers = dict((h, v) for h, v in req_headers.iteritems() if h.lower() not in self.forbidden_headers)

        req_body_len = int(req_headers.get('content-length', 0))
        req_body = self.rfile.read(req_body_len) # bin or str

        payload = {
            'command': self.command, # str
            'path': self.path, # str
            'headers': json.dumps(req_headers), # json
            'payload': lib.btoa(req_body), # str
        }

        #导出并压缩payload
        payload = lib.dumpDict(payload)

        #判断是否需要加密
        if self.path.startswith('https'):
            payload = lib.encrypt(payload)
        else:
            payload = '0' + payload

        # 向GAE获取的过程
        for i in range(4):
            try:
                res = urllib2.urlopen(gaeServer, payload, lib.deadlineRetry[i])
            except (urllib2.URLError, socket.timeout) as e: 
                logging.error(e)
                continue

            if res.code == 200:  # 如果打开GAE没发生错误
                result = res.read()
                result = lib.decrypt(result)
                result = lib.loadDict( result )

                res_status_code = result.status_code
                res_headers = json.loads(result.headers)
                res_content = lib.atob(result.content)
                break
        else:
            # 如果urllib2打开GAE都出错的话,就换个g_opener吧。
            urllib2.install_opener( get_g_opener() ) 

        # 返回数据给浏览器的过程
        try:
            self.send_response(res_status_code) # 200 or or 301 or 404

            res_headers['connection'] = 'close' # 这样不会对速度造成影响,反而能使很多的请求表现得更为准确。
            for k, v in res_headers.iteritems():
                try:
                    self.send_header(k, v)
                except UnicodeEncodeError: # google plus里面就遇到了v包含中文的情况
                    pass
            self.end_headers()
            self.wfile.write(res_content)
        except socket.error, e:
            # 打开了网页后,在数据到达浏览器之前又把网页关闭了而导致的错误。
            logging.error(e)
Exemple #12
0
    def do_GET(self):

        # headers is a dict-like object, it doesn't have `iteritems` method, so convert it to `dict`
        req_headers = dict(self.headers)  # dict
        req_headers = dict((h, v) for h, v in req_headers.iteritems() if h.lower() not in self.forbidden_headers)

        req_body_len = int(req_headers.get("content-length", 0))
        req_body = self.rfile.read(req_body_len)  # bin or str

        payload = {
            "command": self.command,  # str
            "path": self.path,  # str
            "headers": json.dumps(req_headers),  # json
            "payload": lib.btoa(req_body),  # str
        }

        # 导出并压缩payload
        payload = lib.dumpDict(payload)

        # 判断是否需要加密
        if self.path.startswith("https"):
            payload = lib.encrypt(payload)
        else:
            payload = "0" + payload

        # 向GAE获取的过程
        for i in range(4):
            try:
                res = urllib2.urlopen(gaeServer, payload, lib.deadlineRetry[i])
            except (urllib2.URLError, socket.timeout) as e:
                logging.error(e)
                continue

            if res.code == 200:  # 如果打开GAE没发生错误
                result = res.read()
                result = lib.decrypt(result)
                result = lib.loadDict(result)

                res_status_code = result.status_code
                res_headers = json.loads(result.headers)
                res_content = lib.atob(result.content)
                break
        else:
            # 如果urllib2打开GAE都出错的话,就换个g_opener吧。
            urllib2.install_opener(get_g_opener())

        # 返回数据给浏览器的过程
        try:
            self.send_response(res_status_code)  # 200 or or 301 or 404

            res_headers["connection"] = "close"  # 这样不会对速度造成影响,反而能使很多的请求表现得更为准确。
            for k, v in res_headers.iteritems():
                try:
                    self.send_header(k, v)
                except UnicodeEncodeError:  # google plus里面就遇到了v包含中文的情况
                    pass
            self.end_headers()
            self.wfile.write(res_content)
        except socket.error, e:
            # 打开了网页后,在数据到达浏览器之前又把网页关闭了而导致的错误。
            logging.error(e)