Beispiel #1
0
 def getPrivateKey(self):
     if not hasattr(self, 'rsaEngine'):
         self.rsaEngine = RSA()
         self.conf = getConfig()
         fname = self.conf.website.rsakey.privatekey
         self.privatekey = self.rsaEngine.read_privatekey(fname)
     return self.privatekey
Beispiel #2
0
 def __init__(self, myname, privatefile, coding='utf-8'):
     self.rsa = RSA()
     self.rc4 = RC4()
     self.nodes = {}
     self.myname = myname
     self.coding = coding
     self.private_key = self.rsa.read_privatekey(privatefile)
     self.public_key = self.rsa.create_publickey(self.private_key)
Beispiel #3
0
class PeerData:
    def getPeerPublickey(self, peername):
        pass

    def getPeerAddr(self, peername):
        pass

    def setPeerAddr(self, peername, addr):
        pass

    def __init__(self, myname, privatefile, coding='utf-8'):
        self.rsa = RSA()
        self.rc4 = RC4()
        self.nodes = {}
        self.myname = myname
        self.coding = coding
        self.private_key = self.rsa.read_privatekey(privatefile)
        self.public_key = self.rsa.create_publickey(self.private_key)

    def getReceivedData(self, transferBytes, addr):
        crypted, zipped, sender, receiver, body = transferBytes.split('|+|')
        if receiver != self.myname:
            return None
        self.setPeerAddr(sender, addr)
        if crypted == '0':
            d = json.loads(body)
            d['sender'] = sender
            d['receiver'] = receiver
            d['sender_addr'] = addr
            return DictObject(**d)
        cryptedkey, sign, cryptedText = body.split('|@|')
        key = self.rsa.decode(self.private_key, cryptedkey)
        text = rc4.decode(cryptText, key)
        spubk = self.rsa.publickeyFromText(self.getPeerPublickey(sender))
        r = self.rsa.check_sign(spubk, text, sign)
        if not r:
            return None
        d = json.loads(text)
        d['sender'] = sender
        d['receiver'] = receiver
        d['sender_addr'] = addr
        return DictObject(**d)

    def setSendData(self, receiver, text, crypted='0', zipped='0'):
        if receiver is None:
            print('Error**********,receiver is None')
            raise Exception('receiver is None')
        if crypted == '0':
            arr = [crypted, '0', self.myname, receiver, text]
            return '|+|'.join(arr)

        rpubk = self.rsa.publickeyFromText(self.getPeerPublickey(receiver))
        key = getID()
        ctext = self.rc4.encode(text, key)
        sign = self.rsa.sign(self.private_key, text)
        cryptedkey = self.rsa.encode(rpubk, key)
        arr = [cryptedkey, sign, ctext]
        return '|@|'.join(arr)
Beispiel #4
0
    def __init__(self):
        self.config = getConfig()
        self.peertasks = {}
        self.rsaobj = RSA()
        self.center_addr = gethostbyname(self.config.center), \
           self.config.port
        self.direct_addrs = {}

        self.cpd = NodePeerData(config.nodeid, config.privatekey)
        self.cpd.publickeys = {}
        self.local_ip = getlocalip()
        self.commands = {
            "greeting": self.greeting,
            "heartbeatresp": self.heartbeatresp,
            "getpeerinforesp": self.getpeerinforesp,
            "forwardmsg": self.forwardmsg,
            "peer_connect": self.peer_connect,
        }
Beispiel #5
0
	def __init__(self):
		self.config = getConfig()
		self.rsaobj = RSA()
		self.nodeinfo = {}
		self.cpd = CenterPeerData(config.nodeid,config.privatekey)
		self.commands={
			"heartbeat":self.heartbeat,
			"getpeerinfo":self.getpeerinfo,
			"onlinelist":self.onlinelist,
		}
Beispiel #6
0
    def __init__(self):
        self.config = getConfig()
        self.rsaobj = RSA()
        self.nodeinfo = {}
        """
		nodeinfo 
		{
			nodeid:"fff",
			publickey:"ffkgrjgr",
			innerinfo:('192.168.1.22',19993),
			internetinfo:('xxx.xxx.xxx.xxx',22232),
			service:{
			}
		}
		"""
        self.cpd = CenterPeerData(config.nodeid, config.privatekey)
        self.commands = {
            "heartbeat": self.heartbeat,
            "getpeerinfo": self.getpeerinfo,
            "onlinelist": self.onlinelist,
        }
Beispiel #7
0
class AuthAPI(AppLogger):
    def __init__(self):
        super().__init__()

    def getPrivateKey(self):
        if not hasattr(self, 'rsaEngine'):
            self.rsaEngine = RSA()
            self.conf = getConfig()
            fname = self.conf.website.rsakey.privatekey
            self.privatekey = self.rsaEngine.read_privatekey(fname)
        return self.privatekey

    def rsaDecode(self, cdata):
        self.getPrivateKey()
        return self.rsaEngine.decode(self.privatekey, cdata)

    def setupAuth(self, app):
        # setup session middleware in aiohttp fashion
        storage = EncryptedCookieStorage(urandom(32))
        aiohttp_session.setup(app, storage)

        # Create an auth ticket mechanism that expires after 1 minute (60
        # seconds), and has a randomly generated secret. Also includes the
        # optional inclusion of the users IP address in the hash
        policy = auth.SessionTktAuthentication(urandom(32),
                                               60,
                                               include_ip=True)

        # setup aiohttp_auth.auth middleware in aiohttp fashion
        auth.setup(app, policy)
        app.middlewares.append(self.checkAuth)
        app.router.add_route('GET', '/logout', self.logout)

    async def checkLogin(self, request):
        """
		authorization header has the format:
		login_method:user_id:auth_code
		"""
        authinfo = request.headers.get('authorization')
        if authinfo is None:
            self.debug('header not include "authorization" info %s' %
                       request.headers)
            raise web.HTTPUnauthorized()

        authdata = self.rsaDecode(authinfo)
        # print('authdata=',authdata)
        alist = authdata.split('::')
        if len(alist) != 3:
            self.debug('auth data format error %s' % authdata)
            raise web.HTTPUnauthorized()

        login_method = alist[0]
        user_id = alist[1]
        password = alist[2]
        if login_method == 'password':
            if await self.checkUserPassword(user_id, password):
                await auth.remember(request, user_id)
                # print('auth success,',user_id, password)
                return user_id
            # print('auth failed')
            raise web.HTTPUnauthorized()
        else:
            # print('auth method unrecognized------------------------')
            raise web.HTTPUnauthorized()

    async def logout(self, request):
        await auth.forget(request)
        return web.Response(body='OK'.encode('utf-8'))

    @web.middleware
    async def checkAuth(self, request, handler):
        path = request.path
        # print(f'*****{path} checkAuth called********')
        if not await self.needAuth(path):
            return await handler(request)
        user = await auth.get_auth(request)
        if user is None:
            # print('-----------auth.get_auth() return None--------------')
            user = await self.checkLogin(request)
            #raise web.HTTPFound(f'/login_form?from_path={path}')
        user_perms = await self.getUserPermissions(user)
        need_perm = await self.getPermissionNeed(path)
        if need_perm in user_perms:
            return await handler(request)
        # print(f'**{path} forbidden**')
        raise web.HTTPForbidden()

    async def needAuth(self, path):
        return False

    async def getPermissionNeed(self, path):
        return 'admin'

    async def checkUserPassword(self, user_id, password):
        return True

    async def getUserPermissions(self, user):
        return ['admin', 'view']
Beispiel #8
0
class NodeProtocol(TextUDPProtocol):
    def __init__(self):
        self.config = getConfig()
        self.peertasks = {}
        self.rsaobj = RSA()
        self.center_addr = gethostbyname(self.config.center), \
           self.config.port
        self.direct_addrs = {}

        self.cpd = NodePeerData(config.nodeid, config.privatekey)
        self.cpd.publickeys = {}
        self.local_ip = getlocalip()
        self.commands = {
            "greeting": self.greeting,
            "heartbeatresp": self.heartbeatresp,
            "getpeerinforesp": self.getpeerinforesp,
            "forwardmsg": self.forwardmsg,
            "peer_connect": self.peer_connect,
        }

    def on_recv(self, data, addr):
        data = self.cpd.getReceivedData(data, addr)
        func = self.commands.get(data.cmd)
        if func == None:
            print(self.config.nodeid, data.cmd, ' not defined', data,
                  type(data.cmd))
            return
        return func(data)

    def greeting(self, d):
        print(self.config.nodeid, 'greeting(),d=', d)
        self.peertasks[d.sender].cancel()
        d.cnt = d.cnt + 1
        if d.cnt > 1:
            return
        f = d.fromnode
        d.fromnode = d.tonode
        d.tonode = f
        addr = d.sender_addr
        reciever = d.sender
        del d['sender']
        del d['receiver']
        text = json.dumps(d)
        msg = self.cpd.setSendData(receiver, text)
        self.send(msg, addr)

    def peer_connect(self, d):
        print(self.config.nodeid, 'peer_connect(),d=', d)
        self.direct_addrs[d.sender] = d.sender_addr
        d = {
            "cmd": "greeting",
            "msg": "Hello peer ",
            "fromnode": self.config.nodeid,
            "cnt": 0,
            "tonode": d.sender
        }
        text = json.dumps(d)
        msg = self.cpd.setSendData(d.sender, text)
        self.send(msg, d.sender_addr)

    def onlinelist(self):
        req = {"cmd": "onlinelist"}
        text = json.dumps(req)
        msg = self.cpd.setSendData(self.config.center, text)
        self.send(msg, self.center_addr)

    def onlinelistresp(self, d):
        self.onlines = d.onlinelist

    def heartbeat(self):
        dat = {
            "cmd": "heartbeat",
            "nodeid": self.config.nodeid,
            "publickey": self.rsaobj.publickeyText(self.cpd.public_key),
            "innerinfo": (self.local_ip, self.config.port),
        }
        # print('heartbeat=',dat,self.config.nodeid)
        txt = json.dumps(dat)
        msg = self.cpd.setSendData(self.config.center, txt)
        self.send(msg, self.center_addr)
        self.loop.call_later(self.config.heartbeat_timeout or 30,
                             self.heartbeat)

    def heartbeatresp(self, d):
        """
		{
			"cmd":"heartbeatresp",
			"internetinfo":d.sender_addr
		}
		"""
        print(self.config.nodeid, 'heartbeatresp(),d=', d.internetinfo)
        self.internet_addr = d.internetinfo

    def getpeerinfo(self, peername):
        """
		{
			"cmd":"getpeerinfo",
			"peername":"peername"
		}
		"""
        self.loop.call_later(15, self.getpeerinfo, peername)
        d = {"cmd": "getpeerinfo", "peername": peername}
        print(self.config.nodeid, 'getpeerinfo(),d=', d)
        txt = json.dumps(d)
        msg = self.cpd.setSendData(self.config.center, txt)
        self.send(msg, self.center_addr)

    def isSameNAT(self, addr):
        ips = addr[0].split('.')
        myips = self.local_ip.split('.')
        if ips[:3] == myips[:3] and ips[3] != myips[3]:
            return True
        return False

    def getpeerinforesp(self, d):
        """
		{
			"cmd":"getpeerinforesp"
			"publickey":rpubk,
			"peername":d.nodeid,
			"internetinfo":addr,
			"innerinfo":addr1
		}
		"""
        print(self.config.nodeid, 'getpeeriforesp(),d=', d.internetinfo)
        rpubk = d.publickey
        self.cpd.publickeys[d.peername] = rpubk
        retdata = {
            "cmd": "peer_connect",
            "to_addr": d.internetinfo,
            "from_addr": self.internet_addr
        }
        text = json.dumps(retdata)
        msg = self.cpd.setSendData(d.nodeid, text)
        addr = tuple(d.internetinfo)
        self.try_connect(msg, addr, d.nodeid)

    def try_connect(self, msg, addr, peername):
        print(self.config.nodeid, 'try connect to', peername, addr)
        task = self.loop.call_later(0.5, self.try_connect, msg, addr, peername)
        self.peertasks[peername] = task
        self.send(msg, addr)

    def forwardmsg(self, d):
        """
		{
			"cmd":"forwardmsg",
			"forwardfrom":"xxx",
			"forwardto":peername,
			"forwarddata":{
			}
		}
		"""
        print(self.config.nodeid, 'forwardmsg(),d=', d.forwarddata.nodeid,
              d.forwarddata.internetinfo)
        if d.forwardto != self.config.nodeid:
            print(self.config.nodeid, 'forwardto is not me', d.forwardto)
            return

        if d.forwardfrom != d.forwarddata.nodeid:
            return

        b2a = {
            "cmd": "peer_connect",
            "to_addr": d.forwarddata.internetinfo,
            "from_addr": self.internet_addr
        }
        txt = json.dumps(b2a)
        msg = self.cpd.setSendData(d.forwardfrom, json.dumps(d))
        addr = tuple(d.forwarddata.internetinfo)
        self.try_connect(msg, addr, d.forwardfrom)
Beispiel #9
0
class ACBase:
    """
	网站访问控制基本类
	需要继承此类,并实现checkPassword,和checkUserPrivilege两个函数
	使用例子:
	class MyAC(ACBase):
		def checkPassword(self,user,password):
			myusers= {
				'root':'pwd123'
				'user1':'pwd123'
			}
			p = myusers.get(user,None)
			if p == None:
				return False
			if p != password:
				return False
			return True
		def checkUserPrivilege(self,user,path):
			# 用户可以做任何操作
			return True
		
	在需要控制的地方
	ac = MyAC()
	if not ac.accessCheck(request):
		#拒绝操作
	# 正常操作
	"""
    def __init__(self):
        self.conf = getConfig()
        self.rsaEngine = RSA()
        fname = self.conf.website.rsakey.privatekey
        self.privatekey = self.rsaEngine.read_privatekey(fname, 'ymq123')

    def _selectParseHeader(self, authheader):
        txt = self.rsaEngine.decode(self.privatekey, authheader)
        return txt.split(':')

    def checkUserPrivilege(self, user, path):
        raise NotImplementYet

    def checkPassword(self, user, password):
        raise NotImplementYet

    def getRequestUserPassword(self, request):
        try:
            authheader = request.getHeader(b'authorization')
            if authheader is not None:
                return self._selectParseHeader(authheader)
            return None, None
        except Exception as e:
            return 'Anonymous', None

    def isNeedLogin(self, path):
        raise NotImplementYet

    def acCheck(self, request):
        path = self.resource.extract_path(request)
        ws = WebsiteSessiones()
        user = ws.getUserid(request)
        if user == None:
            user, password = self.getRequestUserPassword(request)
            if user is None:
                raise UserNeedLogin(path)
            if not self.checkPassword(user, password):
                raise UserNeedLogin(path)
            ws.login(request, user)

        if not self.checkUserPrivilege(user, path):
            raise UnauthorityResource()
        return True

    def accessCheck(self, request: Request):
        """
		检查用户是否由权限访问此url
		"""
        path = self.resource.extract_path(request)
        if self.isNeedLogin(path):
            # print('need login')
            return self.acCheck(request)
        #没在配置文件设定的路径不做控制,可以随意访问
        # print('not need login')
        return True
Beispiel #10
0
 def __init__(self):
     self.conf = getConfig()
     self.rsaEngine = RSA()
     fname = self.conf.website.rsakey.privatekey
     self.privatekey = self.rsaEngine.read_privatekey(fname, 'ymq123')
Beispiel #11
0
 def __init__(self, myid, myPrikey, pearPubKey=None):
     self.myid = myid
     self.mypri = myPrikey
     self.peerpub = pearPubKey
     self.rsa = RSA()
Beispiel #12
0
class RSAPeer:
    def __init__(self, myid, myPrikey, pearPubKey=None):
        self.myid = myid
        self.mypri = myPrikey
        self.peerpub = pearPubKey
        self.rsa = RSA()

    def getPeerPublicKey(self, id):
        pass

    def _genSystematicKey(self):
        t = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~!@#$%^&*'
        kl = random.randint(10, 15)
        ky = []
        klen = len(t) - 1
        for k in range(kl):
            i = random.randint(0, klen)
            # print(k,klen,i)
            ky.append(t[i])
        return ''.join(ky)

    def encode(self, text):
        """
		return a json text
		json ojbect have three addt:
		k:encrypted rc4 key
		s:signature
		c:ciphertext encrypted by key
		"""
        d = {"id": self.myid, "data": text}
        text = json.dumps(d)
        sk = self._genSystematicKey()
        rc4 = RC4(sk)
        c = rc4.encode(text)
        s = self.rsa.sign(self.mypri, sk)
        if self.peerpub is None:
            return None
        k = self.rsa.encode(self.peerpub, sk)
        d = {'c': c, 'k': k, 's': s}
        return json.dumps(d)

    def decode(self, body):
        """
		cipher a json text
		json ojbect have three addt:
		k:encrypted rc4 key
		s:signature
		c:ciphertext encrypted by key
		"""
        d = json.loads(body)
        signature = d['s']
        sk = self.rsa.decode(self.mypri, d['k'])
        # print('sk=',sk,'k=',d['k'],type(d['k']))
        rc4 = RC4(sk)
        t = rc4.decode(d['c'])
        d = json.loads(t)
        ret = d['data']
        if self.peerpub is not None and not self.rsa.check_sign(
                self.peerpub, sk, signature):
            return None
        if self.peerpub is None:
            peerpub = self.getPeerPublicKey(d['id'])
            if peerpub is None:
                return None
            if not self.rsa.check_sign(peerpub, sk, signature):
                return None
        return ret
Beispiel #13
0
        d = json.loads(t)
        ret = d['data']
        if self.peerpub is not None and not self.rsa.check_sign(
                self.peerpub, sk, signature):
            return None
        if self.peerpub is None:
            peerpub = self.getPeerPublicKey(d['id'])
            if peerpub is None:
                return None
            if not self.rsa.check_sign(peerpub, sk, signature):
                return None
        return ret


if __name__ == '__main__':
    r = RSA()
    mary_pri = r.create_privatekey()
    mary_pub = r.create_publickey(mary_pri)

    john_pri = r.create_privatekey()
    john_pub = r.create_publickey(john_pri)

    john_rp = RSAPeer(john_pri, mary_pub)
    mary_rp = RSAPeer(mary_pri, john_pub)
    txt = '''hello python 爱的实打实大师大师大师的发送到发送到而非个人格个二哥而而二哥而个人各位,UDP是一种无连接对等通信协议,没有服务器和客户端概念,通信的任何一方均可通过通信原语直接和其他方通信
	
HOME FAQ DOCS DOWNLOAD 
 

index
next |