Stop using string exceptions. They were removed in python 2.6.
[mirror/userdir-ldap.git] / sigcheck
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3 #
4 # Check PGP signed emails
5 #
6 # This script verifies the signature on incoming mail for a couple of things
7 #   - That the signature is valid, recent and is not replay
8 #   - The signer is in the LDAP directory and is in the right group
9 #   - The message contains no extra text that is not signed.
10 #
11 # Options:
12 #  -r  Replay cache file, if unset replay checking is disabled
13 #  -k  Colon seperated list of keyrings to use
14 #  -d  LDAP search base DN
15 #  -l  LDAP server
16 #  -g  supplementary group membership
17 #  -p  File of Phrases that must be in the plaintext.
18 #  -m  Disallow PGP/MIME
19 #  -v  Verbose mode
20
21 # Typical Debian invokation may look like:
22 # sigcheck -k /usr/share/keyrings/debian-keyring.gpg:/usr/share/keyrings/debian-keyring.pgp \
23 #      -d ou=users,dc=debian,dc=org -l db.debian.org \
24 #      -m debian.org -a admin@db.debian.org \
25 #      -e /etc/userdir-ldap/templtes/error-reply -- test.sh
26
27 import sys, traceback, time, os;
28 import pwd, getopt;
29 import email, email.parser
30 from userdir_gpg import *;
31
32 EX_TEMPFAIL = 75;
33 EX_PERMFAIL = 65;      # EX_DATAERR
34
35 # Configuration
36 ReplayCacheFile = None;
37 LDAPDn = None;
38 LDAPServer = None;
39 GroupMember = None;
40 Phrases = None;
41 AllowMIME = 1;
42 Verbose = 0;
43
44 class MessageError(Exception):
45    pass
46
47 def verbmsg(msg):
48    if Verbose:
49       sys.stderr.write(msg + "\n")
50
51 # Match the key fingerprint against an LDAP directory
52 def CheckLDAP(FingerPrint):
53    import ldap;
54    import userdir_ldap;
55    
56    # Connect to the ldap server
57    global ErrTyp, ErrMsg;
58    ErrType = EX_TEMPFAIL;
59    ErrMsg = "An error occurred while performing the LDAP lookup:";
60    global l;
61    l = userdir_ldap.connectLDAP(LDAPServer);
62    l.simple_bind_s("","");
63
64    # Search for the matching key fingerprint
65    verbmsg("Processing fingerprint %s" % FingerPrint)
66    Attrs = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + FingerPrint);
67    if len(Attrs) == 0:
68       raise MessageError("Key not found")
69    if len(Attrs) != 1:
70       raise MessageError("Oddly your key fingerprint is assigned to more than one account..")
71
72    gidnumber_found = 0;
73    for key in Attrs[0][1].keys():
74       if (key == "gidNumber"):
75          gidnumber_found = 1
76
77    if (gidnumber_found != 1):
78       raise MessageError("No gidnumber in attributes for fingerprint %s" % FingerPrint)
79
80    # Look for the group with the gid of the user
81    GAttr = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"(&(objectClass=debianGroup)(gidnumber=%s))" % Attrs[0][1]["gidNumber"][0], ["gid"])
82    if len(GAttr) == 0:
83            raise MessageError("Database inconsistency found: main group for account not found in database")
84
85    # See if the group membership is OK
86    # Only if a group was given on the commandline
87    if GroupMember is not None:
88       Hit = 0;
89       # Check primary group first
90       if GAttr[0][1]["gid"][0] == GroupMember:
91          Hit = 1
92       else:
93           # Check supplementary groups
94           for x in Attrs[0][1].get("supplementaryGid",[]):
95               if x == GroupMember:
96                   Hit = 1;
97       if Hit != 1:
98           raise MessageError("You don't have %s group permissions."%(GroupMember))
99    
100 # Start of main program
101 # Process options
102 (options, arguments) = getopt.getopt(sys.argv[1:], "r:k:d:l:g:mp:v");
103 for (switch, val) in options:
104    if (switch == '-r'):
105       ReplayCacheFile = val;
106    elif (switch == '-k'):
107       SetKeyrings(val.split(":"));
108    elif (switch == '-d'):
109       LDAPDn = val;
110    elif (switch == '-l'):
111       LDAPServer = val;
112    elif (switch == '-g'):
113       GroupMember = val;
114    elif (switch == '-m'):
115       AllowMIME = 0;
116    elif (switch == '-v'):
117       Verbose = 1;
118    elif (switch == '-p'):
119       Phrases = val;
120       
121 Now = time.strftime("%a, %d %b %Y %H:%M:%S",time.gmtime(time.time()));
122 ErrMsg = "Indeterminate Error";
123 ErrType = EX_TEMPFAIL;
124 MsgID = None;
125 try:
126    # Startup the replay cache
127    ErrType = EX_TEMPFAIL;
128    if ReplayCacheFile is not None:
129       ErrMsg = "Failed to initialize the replay cache:";
130       RC = ReplayCache(ReplayCacheFile);
131
132    # Get the email 
133    ErrType = EX_PERMFAIL;
134    ErrMsg = "Failed to understand the email or find a signature:";
135    mail = email.parser.Parser().parse(sys.stdin);
136    MsgID = mail["Message-ID"]
137
138    print "Inspecting message %s"%MsgID;
139    verbmsg("Processing message %s" % MsgID)
140    Msg = GetClearSig(mail,1);
141    if AllowMIME == 0 and Msg[1] != 0:
142       raise MessageError("PGP/MIME disallowed")
143   
144    ErrMsg = "Message is not PGP signed:"
145    if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1:
146       raise MessageError("No PGP signature")
147    
148    # Check the signature
149    ErrMsg = "Unable to check the signature or the signature was invalid:";
150    pgp = GPGCheckSig2(Msg[0])
151
152    if not pgp.ok:
153       raise UDFormatError(pgp.why)
154    if pgp.text is None:
155       raise UDFormatError("Null signature text")
156
157    # Check the signature against the replay cache
158    if ReplayCacheFile is not None:
159       RC.process(pgp.sig_info)
160
161    # Do LDAP stuff
162    if LDAPDn is not None:
163       CheckLDAP(pgp.key_fpr)
164
165    ErrMsg = "Verifying message:";
166    if Phrases is not None:
167       F = open(Phrases,"r");
168       while 1:
169           Line = F.readline();
170           if Line == "": break;
171           if pgp.text.find(Line.strip()) == -1:
172               raise MessageError("Phrase '%s' was not found" % (Line.strip()))
173       
174 except:
175    ErrMsg = "[%s] \"%s\" \"%s %s\"\n"%(Now,MsgID,ErrMsg,sys.exc_value);
176    sys.stderr.write(ErrMsg);
177    
178    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
179    List = traceback.extract_tb(sys.exc_traceback);
180    if len(List) >= 1:
181       Trace = Trace + "Python Stack Trace:\n";
182       for x in List:
183          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
184    #print Trace;
185    
186    sys.exit(EX_PERMFAIL);
187
188 # For Main   
189 print "Message %s passed"%MsgID;
190 sys.exit(0);