various bug fixes on the new release of verify_persons
[sfa.git] / clientbin / sfadump.py
1 #! /usr/bin/env python
2 from __future__ import with_statement
3
4 import sys
5 import os, os.path
6 import tempfile
7 from types import StringTypes, ListType
8 from argparse import ArgumentParser
9
10 from sfa.util.sfalogging import logger
11 from sfa.util.faults import CredentialNotVerifiable, CertMissingParent #, ChildRightsNotSubsetOfParent
12
13 from sfa.trust.certificate import Certificate
14 from sfa.trust.credential import Credential
15 from sfa.trust.gid import GID
16
17 from sfa.storage.record import Record
18
19 def determine_sfa_filekind(fn):
20
21     if fn.endswith('.gid'): return 'gid'
22     elif fn.endswith('.cert'): return 'certificate'
23     elif fn.endswith('cred'): return 'credential'
24
25     try:
26         cred=Credential(filename=fn)
27         return 'credential'
28     except: pass
29
30     try: 
31         gid=GID(filename=fn)
32         if gid.uuid: return 'gid'
33     except: pass
34
35     try:
36         cert = Certificate(filename = fn)
37         return 'certificate'
38     except: pass
39
40     # to be completed
41 #    if "gidCaller" in dict:
42 #        return "credential"
43 #
44 #    if "uuid" in dict:
45 #        return "gid"
46
47     return "unknown"
48
49 def save_gid(gid):
50    hrn = gid.get_hrn()
51    lastpart = hrn.split(".")[-1]
52    filename = lastpart + ".gid"
53
54    if os.path.exists(filename):
55        print filename, ": already exists... skipping"
56        return
57
58    print filename, ": extracting gid of", hrn
59
60    gid.save_to_file(filename, save_parents = True)
61
62 def extract_gids(cred, extract_parents):
63    gidCaller = cred.get_gid_caller()
64    if gidCaller:
65        save_gid(gidCaller)
66
67    gidObject = cred.get_gid_object()
68    if gidObject and ((gidCaller == None) or (gidCaller.get_hrn() != gidObject.get_hrn())):
69        save_gid(gidObject)
70
71    # no such method Credential.get_parent
72 #   if extract_parents:
73 #       parent = cred.get_parent()
74 #       if parent:
75 #           extract_gids(parent, extract_parents)
76
77 def verify_input_object (obj, kind, options):
78     if options.trusted_roots:
79         print "CHECKING...",
80         message= "against [" + (" + ".join(options.trusted_roots)) + "]"
81         try:
82             if kind=='credential':
83                 print "verify",message,
84                 obj.verify(options.trusted_roots)
85             elif kind in ['certificate','gid']:
86                 print "verify_chain",message,
87                 obj.verify_chain(options.trusted_roots)
88             print "--> OK"
89         except Exception as inst:
90             print "--> KO",type(inst).__name__
91
92 def handle_input (filename, options):
93     kind = determine_sfa_filekind(filename)
94
95     # dump methods current do 'print' so let's go this road for now
96     if kind=="certificate":
97         cert=Certificate (filename=filename)
98         print '--------------------',filename,'IS A',kind
99         cert.dump(show_extensions=options.show_extensions)
100         verify_input_object (cert, kind, options)
101     elif kind=="credential":
102         cred = Credential(filename = filename)
103         print '--------------------',filename,'IS A',kind
104         cred.dump(dump_parents = options.dump_parents, show_xml=options.show_xml)
105         if options.extract_gids:
106             print '--------------------',filename,'embedded GIDs'
107             extract_gids(cred, extract_parents = options.dump_parents)
108         verify_input_object (cred, kind, options)
109     elif kind=="gid":
110         gid = GID(filename = filename)
111         print '--------------------',filename,'IS A',kind
112         gid.dump(dump_parents = options.dump_parents)
113         verify_input_object (gid, kind, options)
114     else:
115         print "%s: unknown filekind '%s'"% (filename,kind)
116
117 def main():
118     usage = """%(prog)s file1 [ .. filen]
119 display info on input files"""
120     parser = ArgumentParser(usage=usage)
121
122     parser.add_argument("-g", "--extract-gids", action="store_true", dest="extract_gids", 
123                         default=False, help="Extract GIDs from credentials")
124     parser.add_argument("-p", "--dump-parents", action="store_true", dest="dump_parents", 
125                         default=False, help="Show parents")
126     parser.add_argument("-e", "--extensions", action="store_true", 
127                         dest="show_extensions", default="False", help="Show certificate extensions")
128     parser.add_argument("-v", "--verbose", action='count', 
129                         dest='verbose', default=0, help="More and more verbose")
130     parser.add_argument("-x", "--xml", action='store_true', 
131                         dest='show_xml', default=False, help="dumps xml tree (cred. only)")
132     parser.add_argument("-c", "--check", action='append', dest='trusted_roots',
133                         help="cumulative list of trusted GIDs - when provided, the input is verify'ed against these")
134     parser.add_argument("filenames",metavar='F',nargs='+',help="filenames to dump")
135     options = parser.parse_args()
136
137     logger.setLevelFromOptVerbose(options.verbose)
138     for filename in options.filenames: 
139         handle_input(filename,options)
140
141 if __name__=="__main__":
142    main()