Statistics
| Branch: | Tag: | Revision:

root / vncauthproxy / client.py @ 6149f03e

History | View | Annotate | Download (7.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_true', default=False,
80
                      help=("Disable SSL/TLS for control connecions "
81
                            "(default: %s)" % False))
82
    parser.add_option("--ca-cert", dest="ca_cert",
83
                      default=None,
84
                      metavar="CACERT",
85
                      help=("CA certificate file to use for server auth"))
86
    parser.add_option("--strict", dest="strict",
87
                      default=False, action='store_true',
88
                      metavar="STRICT",
89
                      help=("Perform strict authentication on the server "
90
                            "SSL cert"))
91

    
92
    (opts, args) = parser.parse_args(args)
93

    
94
    # Mandatory arguments
95
    if not opts.password:
96
        parser.error("The -P/--password argument is mandatory.")
97
    if not opts.daddr:
98
        parser.error("The -d/--dest argument is mandatory.")
99
    if not opts.dport:
100
        parser.error("The -p/--dport argument is mandatory.")
101
    if not opts.auth_user:
102
        parser.error("The --auth-user argument is mandatory.")
103
    if not opts.auth_password:
104
        parser.error("The --auth-password argument is mandatory.")
105

    
106
    # Sanity check
107
    if opts.strict and not opts.ca_cert:
108
        parser.error("--strict requires --ca-cert to be set")
109
    if opts.no_ssl and opts.ca_cert:
110
        parser.error("--no-ssl and --ca-cert / --strict options "
111
                     "are mutually exclusive")
112

    
113
    return (opts, args)
114

    
115

    
116
def request_forwarding(sport, daddr, dport, password,
117
                       auth_user, auth_password,
118
                       server_address=DEFAULT_SERVER_ADDRESS,
119
                       server_port=DEFAULT_SERVER_PORT, no_ssl=False,
120
                       ca_cert=None, strict=False):
121
    """Connect to vncauthproxy and request a VNC forwarding."""
122
    if not password:
123
        raise ValueError("You must specify a non-empty password")
124

    
125
    req = {
126
        "source_port": int(sport),
127
        "destination_address": daddr,
128
        "destination_port": int(dport),
129
        "password": password,
130
        "auth_user": auth_user,
131
        "auth_password": auth_password,
132
    }
133

    
134
    retries = 5
135
    while retries:
136
        # Initiate server connection
137
        for res in socket.getaddrinfo(server_address, server_port,
138
                                      socket.AF_UNSPEC,
139
                                      socket.SOCK_STREAM, 0,
140
                                      socket.AI_PASSIVE):
141
            af, socktype, proto, canonname, sa = res
142
            try:
143
                server = socket.socket(af, socktype, proto)
144
            except socket.error:
145
                server = None
146
                continue
147

    
148
            if not no_ssl:
149
                reqs = ssl.CERT_NONE
150
                if strict:
151
                    reqs = ssl.CERT_REQUIRED
152
                elif ca_cert:
153
                    reqs = ssl.CERT_OPTIONAL
154

    
155
                server = ssl.wrap_socket(
156
                      server, cert_reqs=reqs, ca_certs=ca_cert,
157
                      ssl_version=ssl.PROTOCOL_TLSv1)
158

    
159
            server.settimeout(60.0)
160

    
161
            try:
162
                server.connect(sa)
163
            except socket.error:
164
                server.close()
165
                server = None
166
                retries -= 1
167
                continue
168

    
169
            retries = 0
170
            break
171

    
172
        sleep(0.2)
173

    
174
    if server is None:
175
        raise Exception("Failed to connect to server")
176

    
177
    server.send(json.dumps(req))
178

    
179
    response = server.recv(1024)
180
    server.close()
181
    res = json.loads(response)
182
    return res
183

    
184

    
185
if __name__ == '__main__':
186
    (opts, args) = parse_arguments(sys.argv[1:])
187

    
188
    res = request_forwarding(sport=opts.sport, daddr=opts.daddr,
189
                             dport=opts.dport, password=opts.password,
190
                             auth_user=opts.auth_user,
191
                             auth_password=opts.auth_password,
192
                             no_ssl=opts.no_ssl, ca_cert=opts.ca_cert,
193
                             strict=opts.strict)
194

    
195
    reason = None
196
    if 'reason' in res:
197
        reason = 'Reason: %s\n' % res['reason']
198
    sys.stderr.write("Forwaring %s -> %s:%s: %s\n%s" % (res['source_port'],
199
                                                      opts.daddr, opts.dport,
200
                                                      res['status'], reason))
201

    
202
    if res['status'] == "OK":
203
        sys.exit(0)
204
    else:
205
        sys.exit(1)