Statistics
| Branch: | Tag: | Revision:

root / vncauthproxy / client.py @ f67f2b8b

History | View | Annotate | Download (7.4 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
""" vncauthproxy client """
21

    
22
import sys
23
import socket
24
import ssl
25

    
26
try:
27
    import simplejson as json
28
except ImportError:
29
    import json
30

    
31
try:
32
    from gevent import sleep
33
except ImportError:
34
    from time import sleep
35

    
36
import logging
37

    
38
DEFAULT_SERVER_ADDRESS = '127.0.0.1'
39
DEFAULT_SERVER_PORT = 24999
40

    
41
logger = logging.getLogger(__name__)
42

    
43

    
44
def parse_arguments(args):
45
    from optparse import OptionParser
46

    
47
    parser = OptionParser()
48
    parser.add_option("--server", dest="server_address",
49
                      default=DEFAULT_SERVER_ADDRESS,
50
                      metavar="SERVER",
51
                      help=("vncauthproxy server address"))
52
    parser.add_option("--server-port", dest="server_port",
53
                      default=DEFAULT_SERVER_PORT, type="int",
54
                      metavar="SERVER_PORT",
55
                      help=("vncauthproxy port"))
56
    parser.add_option('-s', dest="sport",
57
                      default=0, type="int",
58
                      metavar='PORT',
59
                      help=("Use source port PORT for incoming connections "
60
                            "(default: allocate a port automatically)"))
61
    parser.add_option("-d", "--dest",
62
                      default=None, dest="daddr",
63
                      metavar="HOST",
64
                      help="Proxy connection to destination host HOST")
65
    parser.add_option("-p", "--dport", dest="dport",
66
                      default=None, type="int",
67
                      metavar="PORT",
68
                      help="Proxy connection to destination port PORT")
69
    parser.add_option("-P", "--password", dest="password",
70
                      default=None,
71
                      metavar="PASSWORD",
72
                      help=("Use password PASSWD to authenticate incoming "
73
                            "VNC connections"))
74
    parser.add_option("--auth-user", dest="auth_user",
75
                      default=None,
76
                      metavar="AUTH_USER",
77
                      help=("User to authenticate as, for the control "
78
                            "connection"))
79
    parser.add_option("--auth-password", dest="auth_password",
80
                      default=None,
81
                      metavar="AUTH_PASSWORD",
82
                      help=("User password for the control connection "
83
                            "authentication"))
84
    parser.add_option("--enable-ssl", dest="enable_ssl",
85
                      action='store_true', default=False,
86
                      help=("Enable SSL/TLS for control connecions "
87
                            "(default: %s)" % False))
88
    parser.add_option("--ca-cert", dest="ca_cert",
89
                      default=None,
90
                      metavar="CACERT",
91
                      help=("CA certificate file to use for server auth"))
92
    parser.add_option("--strict", dest="strict",
93
                      default=False, action='store_true',
94
                      metavar="STRICT",
95
                      help=("Perform strict authentication on the server "
96
                            "SSL cert"))
97

    
98
    (opts, args) = parser.parse_args(args)
99

    
100
    return (opts, args)
101

    
102

    
103
def request_forwarding(sport, daddr, dport, password,
104
                       auth_user, auth_password,
105
                       server_address=DEFAULT_SERVER_ADDRESS,
106
                       server_port=DEFAULT_SERVER_PORT, enable_ssl=False,
107
                       ca_cert=None, strict=False):
108
    """Connect to vncauthproxy and request a VNC forwarding."""
109

    
110
    # Mandatory arguments
111
    if not password:
112
        raise Exception("The password argument is mandatory.")
113
    if not daddr:
114
        raise Exception("The daddr argument is mandatory.")
115
    if not dport:
116
        raise Exception("The dport argument is mandatory.")
117
    if not auth_user:
118
        raise Exception("The auth_user argument is mandatory.")
119
    if not auth_password:
120
        raise Exception("The auth_password argument is mandatory.")
121

    
122
    # Sanity check
123
    if strict and not ca_cert:
124
        raise Exception("strict requires ca-cert to be set")
125
    if not enable_ssl and (strict or ca_cert):
126
        logger.warning("strict or ca_cert set, but ssl not enabled")
127

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

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

    
152
            if enable_ssl:
153
                reqs = ssl.CERT_NONE
154
                if strict:
155
                    reqs = ssl.CERT_REQUIRED
156
                elif ca_cert:
157
                    reqs = ssl.CERT_OPTIONAL
158

    
159
                server = ssl.wrap_socket(server, cert_reqs=reqs,
160
                                         ca_certs=ca_cert,
161
                                         ssl_version=ssl.PROTOCOL_TLSv1)
162

    
163
            server.settimeout(60.0)
164

    
165
            try:
166
                server.connect(sa)
167
            except socket.error as err:
168
                server.close()
169
                server = None
170
                retries -= 1
171
                last_error = err
172
                continue
173

    
174
            retries = 0
175
            break
176

    
177
        sleep(0.2)
178

    
179
    if server is None:
180
        raise Exception("Failed to connect to server: %s" % last_error)
181

    
182
    server.send(json.dumps(req))
183

    
184
    response = server.recv(1024)
185
    server.close()
186
    res = json.loads(response)
187
    return res
188

    
189

    
190
if __name__ == '__main__':
191
    logger.addHandler(logging.StreamHandler())
192

    
193
    (opts, args) = parse_arguments(sys.argv[1:])
194

    
195
    res = request_forwarding(sport=opts.sport, daddr=opts.daddr,
196
                             dport=opts.dport, password=opts.password,
197
                             auth_user=opts.auth_user,
198
                             auth_password=opts.auth_password,
199
                             enable_ssl=opts.enable_ssl, ca_cert=opts.ca_cert,
200
                             strict=opts.strict)
201

    
202
    reason = None
203
    if 'reason' in res:
204
        reason = 'Reason: %s\n' % res['reason']
205
    sys.stderr.write("Forwaring %s -> %s:%s: %s\n%s" % (res['source_port'],
206
                                                        opts.daddr, opts.dport,
207
                                                        res['status'], reason))
208

    
209
    if res['status'] == "OK":
210
        sys.exit(0)
211
    else:
212
        sys.exit(1)