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