Statistics
| Branch: | Tag: | Revision:

root / vncauthproxy / client.py @ d49bd2fb

History | View | Annotate | Download (6.3 kB)

1
#!/usr/bin/env python
2
#
3
# Copyright (c) 2010-2011 Greek Research and Technology Network S.A.
4
#
5
# This program is free software; you can redistribute it and/or modify
6
# it under the terms of the GNU General Public License as published by
7
# the Free Software Foundation; either version 2 of the License, or
8
# (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful, but
11
# WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13
# General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18
# 02110-1301, USA.
19

    
20
import sys
21
import socket
22
import ssl
23

    
24
try:
25
    import simplejson as json
26
except ImportError:
27
    import json
28

    
29
try:
30
    from gevent import sleep
31
except ImportError:
32
    import sleep
33

    
34
DEFAULT_SERVER_ADDRESS = '127.0.0.1'
35
DEFAULT_SERVER_PORT = 24999
36

    
37

    
38
def parse_arguments(args):
39
    from optparse import OptionParser
40

    
41
    parser = OptionParser()
42
    parser.add_option("--server", dest="server_address",
43
                      default=DEFAULT_SERVER_ADDRESS,
44
                      metavar="SERVER",
45
                      help=("vncauthproxy server address"))
46
    parser.add_option("--server-port", dest="server_port",
47
                      default=DEFAULT_SERVER_PORT, type="int",
48
                      metavar="SERVER_PORT",
49
                      help=("vncauthproxy port"))
50
    parser.add_option('-s', dest="sport",
51
                      default=0, type="int",
52
                      metavar='PORT',
53
                      help=("Use source port PORT for incoming connections "
54
                            "(default: allocate a port automatically)"))
55
    parser.add_option("-d", "--dest",
56
                      default=None, dest="daddr",
57
                      metavar="HOST",
58
                      help="Proxy connection to destination host HOST")
59
    parser.add_option("-p", "--dport", dest="dport",
60
                      default=None, type="int",
61
                      metavar="PORT",
62
                      help="Proxy connection to destination port PORT")
63
    parser.add_option("-P", "--password", dest="password",
64
                      default=None,
65
                      metavar="PASSWORD",
66
                      help=("Use password PASSWD to authenticate incoming "
67
                            "VNC connections"))
68
    parser.add_option("--auth-user", dest="auth_user",
69
                      default=None,
70
                      metavar="AUTH_USER",
71
                      help=("User to authenticate as, for the control "
72
                            "connection"))
73
    parser.add_option("--auth-password", dest="auth_password",
74
                      default=None,
75
                      metavar="AUTH_PASSWORD",
76
                      help=("User password for the control connection "
77
                            "authentication"))
78
    parser.add_option("--no-ssl", dest="no_ssl",
79
                      action='store_false', default=False,
80
                      help=("Disable SSL/TLS for control connecions "
81
                            "(default: %s)" % False))
82

    
83
    (opts, args) = parser.parse_args(args)
84

    
85
    # Mandatory arguments
86
    if not opts.password:
87
        parser.error("The -P/--password argument is mandatory.")
88
    if not opts.daddr:
89
        parser.error("The -d/--dest argument is mandatory.")
90
    if not opts.dport:
91
        parser.error("The -p/--dport argument is mandatory.")
92
    if not opts.auth_user:
93
        parser.error("The --auth-user argument is mandatory.")
94
    if not opts.auth_password:
95
        parser.error("The --auth-password argument is mandatory.")
96

    
97
    return (opts, args)
98

    
99

    
100
def request_forwarding(sport, daddr, dport, password,
101
                       auth_user, auth_password,
102
                       server_address=DEFAULT_SERVER_ADDRESS,
103
                       server_port=DEFAULT_SERVER_PORT, no_ssl=False):
104
    """Connect to vncauthproxy and request a VNC forwarding."""
105
    if not password:
106
        raise ValueError("You must specify a non-empty password")
107

    
108
    req = {
109
        "source_port": int(sport),
110
        "destination_address": daddr,
111
        "destination_port": int(dport),
112
        "password": password,
113
        "auth_user": auth_user,
114
        "auth_password": auth_password,
115
    }
116

    
117
    retries = 5
118
    while retries:
119
        # Initiate server connection
120
        for res in socket.getaddrinfo(server_address, server_port,
121
                                      socket.AF_UNSPEC,
122
                                      socket.SOCK_STREAM, 0,
123
                                      socket.AI_PASSIVE):
124
            af, socktype, proto, canonname, sa = res
125
            try:
126
                server = socket.socket(af, socktype, proto)
127
            except socket.error:
128
                server = None
129
                continue
130

    
131
            if not no_ssl:
132
                server = ssl.wrap_socket(
133
                      server, cert_reqs=ssl.CERT_NONE,
134
                      ssl_version=ssl.PROTOCOL_TLSv1)
135

    
136
            server.settimeout(60.0)
137

    
138
            try:
139
                server.connect(sa)
140
            except socket.error:
141
                server.close()
142
                server = None
143
                retries -= 1
144
                continue
145

    
146
            retries = 0
147
            break
148

    
149
        sleep(0.2)
150

    
151
    if server is None:
152
        raise Exception("Failed to connect to server")
153

    
154
    server.send(json.dumps(req))
155

    
156
    response = server.recv(1024)
157
    server.close()
158
    res = json.loads(response)
159
    return res
160

    
161

    
162
if __name__ == '__main__':
163
    (opts, args) = parse_arguments(sys.argv[1:])
164

    
165
    res = request_forwarding(sport=opts.sport, daddr=opts.daddr,
166
                             dport=opts.dport, password=opts.password,
167
                             auth_user=opts.auth_user,
168
                             auth_password=opts.auth_password,
169
                             no_ssl=opts.no_ssl)
170

    
171
    reason = None
172
    if 'reason' in res:
173
        reason = 'Reason: %s\n' % res['reason']
174
    sys.stderr.write("Forwaring %s -> %s:%s: %s\n%s" % (res['source_port'],
175
                                                      opts.daddr, opts.dport,
176
                                                      res['status'], reason))
177

    
178
    if res['status'] == "OK":
179
        sys.exit(0)
180
    else:
181
        sys.exit(1)