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

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

* Working version for mapped certificates *

ndgSessionClient.py:

  • renamed dict to argDict to avoid clash with existing arg var.
  • added code for handling ext attCert list and trusted host list files.
  • Changed so that --connect and --req-autho can be specified together so that a connect call is

concatenated with a call to request authorisation.

attAuthorityIOtest.py: unit tests for AttAuthorityIO classes.
attCertTest.py: unit tests for AttCert?.

AttAuthorityIO.py:

attAuthority_services_server.py: update and fixes to GetTrustedHostInfo? WS stub.

AttAuthority?.py:

AttCert?.py: !! important fix - added nonzero method so that test on AttCert? instance
yields True e.g. if attCert: ...

Session.py:

  • SessionMgr?.readProperties - only strip white space from XML data if it's string type -

elementtree sets content to None if an empty tag is present in the XML it's reading.

CredWallet?.py: changes to WS calls - use AttAuthorityIO classes - AuthorisationReq/?
AuthorisationResp? + TrustedHostInfoReq/TrustedHostInfoResp?.

  • 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 dictionary
153    argDict = {}.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            argDict['add-user'] = True
166
167        elif opt in ("-c", "--connect"):
168            argDict['connect'] = True
169
170        elif opt in ("-r", "--req-autho"):
171            argDict['req-autho'] = True
172
173        elif opt in ("-s", "--session-mgr-wsdl-uri"):
174            argDict['session-mgr-wsdl-uri'] = arg
175
176        elif opt in ("-a", "--att-authority-wsdl-uri"):
177            argDict['att-authority-wsdl-uri'] = arg
178
179        elif opt in ("-u", "--username"):
180            argDict['username'] = arg
181
182        elif opt in ("-p", "--pass-phrase-from-stdin"):
183            argDict['pass-phrase-from-stdin'] = True
184
185        elif opt in ("-i", "--session-id"):
186            argDict['session-id'] = arg
187
188        elif opt in ("-e", "--encr-sess-mgr-wsdl-uri"):
189            argDict['encr-sess-mgr-wsdl-uri'] = arg
190
191        elif opt in ("-d", "--soap-debug"):
192            argDict['soap-debug'] = sys.stderr
193
194        elif opt in ("-m", "--map-from-trusted-hosts"):
195            argDict['map-from-trusted-hosts'] = True
196               
197        elif opt in ("-q", "--req-role"):
198            argDict['req-role'] = arg
199       
200        elif opt in ("-l", "--rtn-ext-att-cert-list"):
201            argDict['rtn-ext-att-cert-list'] = True
202           
203        elif opt in ("-f", "--ext-att-cert-list-file"):
204            argDict['ext-att-cert-list-file'] = arg
205           
206            try:
207                # Open and read file removing any <?xml ... ?> headers
208                fpExtAttCertList = open(argDict['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*",
224                             open(argDict['ext-trusted-host-file']).read())
225               
226            except Exception, e:
227                sys.stderr.write(\
228                    "Error parsing file \%s\" for option \"%s\": %s" % \
229                    (arg, opt, str(e)))
230                   
231        else:
232            sys.stderr.write("Option not recognised: %s\n\n" % opt)
233            usage(fp=sys.stderr)
234            sys.exit(1)
235
236
237    # For connect/addUser a pass-phrase is needed
238    if argDict['add-user'] or argDict['connect']:
239       
240        if argDict['pass-phrase-from-stdin']:
241            # Read from standard input
242            passPhrase = sys.stdin.read().strip()
243           
244        else:
245            # Obtain from prompt
246            import getpass
247            try:
248#                passPhrase = getpass.getpass(prompt="pass-phrase: ")
249                passPhrase = open('./Tests/tmp').read().strip()
250            except KeyboardInterrupt:
251                sys.exit(1)
252
253
254    # Initialise session client
255    try:
256        sessClnt = SessionClient(smWSDL=argDict['session-mgr-wsdl-uri'],
257                                 traceFile=argDict['soap-debug'])
258    except Exception, e:
259        sys.stderr.write("Initialising client: %s\n" % str(e))
260        sys.exit(1)
261       
262    try:
263        if argDict['add-user']:
264            sessClnt.addUser(userName=argDict['username'], pPhrase=passPhrase)
265            sys.exit(0)
266                           
267        if argDict['connect']:
268            sSessCookie = sessClnt.connect(userName=argDict['username'], 
269                                           pPhrase=passPhrase)           
270            print sSessCookie
271            # Don't exit here - req-autho may have been set too
272   
273        if argDict['req-autho']:
274            if argDict['connect']:
275                # Connect was set also - parse cookie in order to session ID
276                # and WSDL address
277                from Cookie import SimpleCookie
278                sessCookie = SimpleCookie(sSessCookie)
279               
280                argDict['session-id'] = sessCookie['NDG-ID1'].value
281                argDict['encr-sess-mgr-wsdl-uri']=sessCookie['NDG-ID2'].value
282               
283            authResp = sessClnt.reqAuthorisation(\
284                        sessID=argDict['session-id'], 
285                        encrSessMgrWSDLuri=argDict['encr-sess-mgr-wsdl-uri'],
286                        aaWSDL=argDict['att-authority-wsdl-uri'],
287                        mapFromTrustedHosts=argDict['map-from-trusted-hosts'],
288                        reqRole=argDict['req-role'],
289                        rtnExtAttCertList=argDict['rtn-ext-att-cert-list'],
290                        extAttCertList=extAttCertList,
291                        extTrustedHostList=extTrustedHostList)
292            print authResp
293        else:   
294            sys.stderr.write(\
295            "Set a flag to specify the web-service call e.g. --connect\n\n")
296            usage(fp=sys.stderr)
297            sys.exit(1)
298           
299    except Exception, e:
300        sys.stderr.write(str(e) + os.linesep)
301     
302    sys.exit(0)
Note: See TracBrowser for help on using the repository browser.