2 Wrapper for Invirt VNC proxying
6 from twisted.internet import reactor, protocol, defer
7 from twisted.python import log
23 return file('/etc/invirt/secrets/vnc-key').read().strip()
25 def getPort(name, auth_data):
27 if (auth_data["machine"] == name):
28 port = get_port.findPort(name)
31 return int(port.split(':')[1])
35 class VNCAuthOutgoing(protocol.Protocol):
37 def __init__(self,socks):
40 def connectionMade(self):
41 peer = self.transport.getPeer()
42 self.socks.makeReply(200)
43 self.socks.otherConn=self
45 def connectionLost(self, reason):
46 self.socks.transport.loseConnection()
48 def dataReceived(self,data):
49 self.socks.write(data)
52 self.transport.write(data)
55 class VNCAuth(protocol.Protocol):
57 def __init__(self,server="localhost"):
61 def connectionMade(self):
65 def validateToken(self, token):
66 self.auth_error = "Invalid token"
68 token = base64.urlsafe_b64decode(token)
69 token = cPickle.loads(token)
70 m = hmac.new(getTokenKey(), digestmod=sha)
71 m.update(token['data'])
72 if (m.digest() == token['digest']):
73 data = cPickle.loads(token['data'])
74 expires = data["expires"]
75 if (time.time() < expires):
76 self.auth = data["user"]
77 self.auth_error = None
78 self.auth_machine = data["machine"]
81 self.auth_error = "Token has expired; please try logging in again"
82 except (TypeError, cPickle.UnpicklingError):
86 def dataReceived(self,data):
88 self.otherConn.write(data)
90 self.buf=self.buf+data
91 if ('\r\n\r\n' in self.buf) or ('\n\n' in self.buf) or ('\r\r' in self.buf):
92 lines = self.buf.splitlines()
93 args = lines.pop(0).split()
98 (header, data) = line.split(": ", 1)
99 headers[header] = data
103 if command == "AUTHTOKEN":
105 token = headers["Auth-token"]
106 if token == "1": #FIXME
108 self.makeReply(200, "Authentication successful")
111 elif command == "CONNECTVNC":
113 if ("Auth-token" in headers):
114 token = headers["Auth-token"]
115 self.validateToken(token)
116 if self.auth is not None:
117 port = getPort(vmname, self.auth_data)
118 if port is not None: # FIXME
120 d = self.connectClass(self.server, port, VNCAuthOutgoing, self)
121 d.addErrback(lambda result, self=self: self.makeReply(404, result.getErrorMessage()))
123 self.makeReply(404, "Unable to find VNC for VM "+vmname)
125 self.makeReply(401, "Unauthorized to connect to VM "+vmname)
128 self.makeReply(401, self.auth_error)
130 self.makeReply(401, "Invalid token")
132 self.makeReply(401, "Login first")
134 self.makeReply(501, "unknown method "+command)
136 if False and '\000' in self.buf[8:]:
137 head,self.buf=self.buf[:8],self.buf[8:]
139 version,code,port=struct.unpack("!BBH",head[:4])
141 raise RuntimeError, "struct error with head='%s' and buf='%s'"%(repr(head),repr(self.buf))
142 user,self.buf=string.split(self.buf,"\000",1)
143 if head[4:7]=="\000\000\000": # domain is after
144 server,self.buf=string.split(self.buf,'\000',1)
145 #server=gethostbyname(server)
147 server=socket.inet_ntoa(head[4:8])
148 assert version==4, "Bad version code: %s"%version
149 if not self.authorize(code,server,port,user):
152 if code==1: # CONNECT
153 d = self.connectClass(server, port, SOCKSv4Outgoing, self)
154 d.addErrback(lambda result, self=self: self.makeReply(91))
156 raise RuntimeError, "Bad Connect Code: %s" % code
157 assert self.buf=="","hmm, still stuff in buffer... %s" % repr(self.buf)
159 def connectionLost(self, reason):
161 self.otherConn.transport.loseConnection()
163 def authorize(self,code,server,port,user):
164 log.msg("code %s connection to %s:%s (user %s) authorized" % (code,server,port,user))
167 def connectClass(self, host, port, klass, *args):
168 return protocol.ClientCreator(reactor, klass, *args).connectTCP(host,port)
170 def makeReply(self,reply,message=""):
171 self.transport.write("VNCProxy/1.0 %d %s\r\n\r\n" % (reply, message))
172 if int(reply / 100)!=2: self.transport.loseConnection()
174 def write(self,data):
175 self.transport.write(data)
177 def log(self,proto,data):
178 peer = self.transport.getPeer()
179 their_peer = self.otherConn.transport.getPeer()
180 print "%s\t%s:%d %s %s:%d\n"%(time.ctime(),
182 ((proto==self and '<') or '>'),
183 their_peer.host,their_peer.port),
185 p,data=data[:16],data[16:]
186 print string.join(map(lambda x:'%02X'%ord(x),p),' ')+' ',
187 print ((16-len(p))*3*' '),
189 if len(repr(c))>3: print '.',
195 class VNCAuthFactory(protocol.Factory):
196 """A factory for a VNC auth proxy.
198 Constructor accepts one argument, a log file name.
201 def __init__(self, server):
204 def buildProtocol(self, addr):
205 return VNCAuth(self.server)