source: TI12-security/trunk/python/ndgSessionClient.py @ 668

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI12-security/trunk/python/ndgSessionClient.py@668
Revision 668, 10.4 KB checked in by pjkersha, 15 years ago (diff)

ndgSessionClient.py: added option for authorisation requests and also the ability to
combine --connect and --req-autho calls.

sessionMgrProperties.xml: new property cookieDomain enables a specific domain to be set for
session cookie.

Session.py: changes to implement the above - UserSession? has a cookieDomain attribute and
cookieDomain property.

  • Property svn:executable set to *
Line 
1#!/usr/bin/env python
2
3"""NDG Session client script - makes requests for authentication and
4authorisation
5
6NERC Data Grid Project
7
8P J Kershaw 08/03/06
9
10Copyright (C) 2006 CCLRC & NERC
11
12This software may be distributed under the terms of the Q Public License,
13version 1.0 or later.
14"""
15# Command line processing
16import sys
17import os
18import getopt
19import re
20
21from NDG.SessionClient import *
22
23
24#_____________________________________________________________________________
25def usage(fp=sys.stdout):
26    """Describes how to call session client from the command line"""
27    progName = os.path.basename(sys.argv[0])
28   
29    fp.write(\
30    """usage: %s [--add-user|--connect|--req-autho]|[--connect --req-autho]
31        [<args...>]%s""" % (progName, os.linesep))
32       
33    fp.write("""   
34-h | --help
35    print usage summary
36
37Web-service calls:
38   
39-n | --add-user
40    add a new user:
41       
42    %s --add-user -u <username> [-p] -s <Session Manager WSDL URI>
43
44-c | --connect
45    login in to a Session Manager
46   
47    %s --connect -u <username> [-p] -s <Session Manager WSDL URI>
48   
49-r | --req-autho
50    Get a Session Manager to request authorisation from an Attribute
51    Authority on behalf of a user:
52   
53    %s --req-autho -i <User's Session ID> -s <Session Manager WSDL URI>
54    -a <Attribute Authority WSDL URI> [-m -q <role name> -l -f <file path>
55    -t <file path>]
56 
57Generic options:
58   
59-s <Session Manager WSDL URI> |
60 --session-mgr-wsdl-uri=<Session Manager WSDL URI>
61    Address of Session Manager to connect to.
62     
63-d  | --soap-debug
64    Print SOAP message output.
65
66Options specific to --connect and --add-user:
67   
68-u <username> | --username=<username>
69    username for --connect call
70
71-p | --pass-phrase-from-stdin
72    Take user's pass-phrase from stdin.  If this flag is omitted, pass-phrase
73    is prompted for.
74
75Options specific to --req-autho:
76   
77-i <session ID> | --sessionID=<Session ID>
78    Session ID for --req-autho call.  Session ID is obtained from the cookie
79    returned from previous call to "%s --connect ..."
80   
81-e <encrypted Session Manager WSDL URI> |
82 --encr-sess-mgr-wsdl-uri <encrypted Session Manager WSDL URI>
83    Encrypted address of Session Manager where user session is held.  This is
84    obtained from the cookie returned from call to "%s --connect ..."
85   
86-a <Attribute Authority WSDL URI> |
87 --att-authority-wsdl-uri=<Attribute Authority WSDL URI>
88    The address of the Attribute Authority from which to request an
89    Attribute Certificate.
90
91-m | --map-from-trusted-hosts
92    Set to allow the Session Manager to automatically use Attribute
93    Certificates from the user's wallet or if no suitable ones are found,
94    to contact other trusted hosts in order to get Attribute Certificates
95    for mapping.
96   
97-q <role name> | --req-role=<role name>
98    Give a hint to the authorisation request as to what role is needed in
99    order to get a mapped Attribute Certificate back from the Attribute
100    Authority.
101   
102-l | --rtn-ext-att-cert-list
103    Determines behaviour for where authorisation is denied by an Attribute
104    Authority.   If set, a list of candidate Attribute Certificates from
105    trusted import hosts will be returned.  Any one of these could be
106    re-input in a subsequent with the --ext-att-cert-list-file option in order
107    to get a mapped Attribute Certificate
108   
109-f <file path> | --ext-att-cert-list-file=<file path>
110    file of concatenated Attribute Certificates.  These are certificates
111    from other import hosts trusted by the Attribute Authority.  The Session
112    Manager tries each in turn until the Attribute Authority accepts one
113    and uses it to create and return a mapped Attribute Certificate.
114   
115-t | --ext-trusted-host-file=<comma separated variable file>
116    For use with --req-autho flag.  Pass a file containing a list of hosts
117    trusted by the Attribute Authority.  The Session Manager will contact
118    these hosts in turn until it can get an Attribute Certificate to pass
119    to the Attribute Authority to get a mapped Attribute Certificate in
120    return.
121""" % (progName, progName, progName, progName, progName))
122
123
124#_____________________________________________________________________________
125if __name__ == '__main__':
126
127    try:
128        optLongNames = [ "help",
129                         "add-user", 
130                         "connect",
131                         "req-autho",
132                         "session-mgr-wsdl-uri=", 
133                         "att-authority-wsdl-uri=",
134                         "username=",
135                         "pass-phrase-from-stdin",
136                         "session-id=",
137                         "encr-sess-mgr-wsdl-uri",
138                         "soap-debug",
139                         "map-from-trusted-hosts",
140                         "req-role=",
141                         "rtn-ext-att-cert-list",
142                         "ext-att-cert-list-file=",
143                         "ext-trusted-host-file="]
144        optShortNames = "hncrs:a:u:pi:e:dmq:lf:t:"
145        opts, args = getopt.getopt(sys.argv[1:], optShortNames, optLongNames)
146
147    except getopt.GetoptError, e:
148        sys.stderr.write("Error: %s\n\n" % e)
149        usage(fp=sys.stderr)
150        sys.exit(1)
151
152    # Use long options to make a disctionary
153    args = {}.fromkeys([opt.split('=')[0] for opt in optLongNames])
154   
155    extTrustedHostList = None
156    extAttCertList = None
157    passPhrase = None
158   
159    for opt, arg in opts:
160        if opt in ("-h", "--help"):
161            usage()
162            sys.exit(0)
163
164        elif opt in ("-n", "--add-user"):
165            args['add-user'] = True
166
167        elif opt in ("-c", "--connect"):
168            args['connect'] = True
169
170        elif opt in ("-r", "--req-autho"):
171            args['req-autho'] = True
172
173        elif opt in ("-s", "--session-mgr-wsdl-uri"):
174            args['session-mgr-wsdl-uri'] = arg
175
176        elif opt in ("-a", "--att-authority-wsdl-uri"):
177            args['att-authority-wsdl-uri'] = arg
178
179        elif opt in ("-u", "--username"):
180            args['username'] = arg
181
182        elif opt in ("-p", "--pass-phrase-from-stdin"):
183            args['pass-phrase-from-stdin'] = True
184
185        elif opt in ("-i", "--session-id"):
186            args['session-id'] = arg
187
188        elif opt in ("-e", "--encr-sess-mgr-wsdl-uri"):
189            args['encr-sess-mgr-wsdl-uri'] = arg
190
191        elif opt in ("-d", "--soap-debug"):
192            args['soap-debug'] = sys.stderr
193
194        elif opt in ("-m", "--map-from-trusted-hosts"):
195            args['map-from-trusted-hosts'] = True
196               
197        elif opt in ("-q", "--req-role"):
198            args['req-role'] = arg
199       
200        elif opt in ("-l", "--rtn-ext-att-cert-list"):
201            args['rtn-ext-att-cert-list'] = True
202           
203        elif opt in ("-f", "--ext-att-cert-list-file"):
204            args['ext-att-cert-list-file'] = arg
205           
206            try:
207                # Open and read file removing any <?xml ... ?> headers
208                fpExtAttCertList = open(args['ext-att-cert-list-file'])
209                sAttCertList = \
210                     re.sub("\s*<\?xml.*\?>\s*", "", fpExtAttCertList.read())
211               
212                # Convert into a list
213                extAttCertList = ['<attributeCertificate>' + ac for ac in \
214                            sAttCertList.split('<attributeCertificate>')[1:]]
215            except Exception, e:
216                sys.stderr.write(\
217                    "Error parsing file \%s\" for option \"%s\": %s" % \
218                    (arg, opt, str(e)))
219           
220        elif opt in ("-t", "ext-trusted-host-file"):
221            try:
222                extTrustedHostList = \
223                re.split("\s*,\s*",open(args['ext-trusted-host-file']).read())
224               
225            except Exception, e:
226                sys.stderr.write(\
227                    "Error parsing file \%s\" for option \"%s\": %s" % \
228                    (arg, opt, str(e)))
229                   
230        else:
231            sys.stderr.write("Option not recognised: %s\n\n" % opt)
232            usage(fp=sys.stderr)
233            sys.exit(1)
234
235
236    # For connect/addUser a pass-phrase is needed
237    if args['add-user'] or args['connect']:
238       
239        if args['pass-phrase-from-stdin']:
240            # Read from standard input
241            passPhrase = sys.stdin.read().strip()
242           
243        else:
244            # Obtain from prompt
245            import getpass
246            try:
247                passPhrase = getpass.getpass(prompt="pass-phrase: ")               
248            except KeyboardInterrupt:
249                sys.exit(1)
250
251
252    # Initialise session client
253    try:
254        sessClnt = SessionClient(smWSDL=args['session-mgr-wsdl-uri'],
255                                 traceFile=args['soap-debug'])
256    except Exception, e:
257        sys.stderr.write("Initialising client: %s\n" % str(e))
258        sys.exit(1)
259       
260    try:
261        if args['add-user']:
262            sessClnt.addUser(userName=args['username'], pPhrase=passPhrase)
263            sys.exit(0)
264                           
265        if args['connect']:
266            sSessCookie = sessClnt.connect(userName=args['username'], 
267                                           pPhrase=passPhrase)           
268            print sSessCookie
269            # Don't exit here - req-autho may have been set too
270   
271        if args['req-autho']:
272            if args['connect']:
273                # Connect was set also - parse cookie in order to session ID
274                # and WSDL address
275                from Cookie import SimpleCookie
276                sessCookie = SimpleCookie(sSessCookie)
277               
278                args['session-id'] = sessCookie['NDG-ID1'].value
279                args['encr-sess-mgr-wsdl-uri'] = sessCookie['NDG-ID2'].value
280               
281            authResp = sessClnt.reqAuthorisation(\
282                        sessID=args['session-id'], 
283                        encrSessMgrWSDLuri=args['encr-sess-mgr-wsdl-uri'],
284                        aaWSDL=args['att-authority-wsdl-uri'],
285                        mapFromTrustedHosts=args['map-from-trusted-hosts'],
286                        reqRole=args['req-role'],
287                        rtnExtAttCertList=args['rtn-ext-att-cert-list'],
288                        extAttCertList=extAttCertList,
289                        extTrustedHostList=extTrustedHostList)
290            print authResp
291        else:   
292            sys.stderr.write(\
293            "Set a flag to specify the web-service call e.g. --connect\n\n")
294            usage(fp=sys.stderr)
295            sys.exit(1)
296           
297    except Exception, e:
298        sys.stderr.write(str(e) + os.linesep)
299     
300    sys.exit(0)
Note: See TracBrowser for help on using the repository browser.