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