Sig checker
[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
20 # Typical Debian invokation may look like:
21 # ./gpgwrapper -k /usr/share/keyrings/debian-keyring.gpg:/usr/share/keyrings/debian-keyring.pgp \
22 #      -d ou=users,dc=debian,dc=org -l db.debian.org \
23 #      -m debian.org -a admin@db.debian.org \
24 #      -e /etc/userdir-ldap/templtes/error-reply -- test.sh
25
26 import sys, traceback, time, os;
27 import string, pwd, getopt;
28 from userdir_gpg import *;
29
30 EX_TEMPFAIL = 75;
31 EX_PERMFAIL = 65;      # EX_DATAERR
32 Error = 'Message Error';
33
34 # Configuration
35 ReplayCacheFile = None;
36 LDAPDn = None;
37 LDAPServer = None;
38 GroupMember = None;
39 Phrases = None;
40 AllowMIME = 1;
41
42 # Match the key fingerprint against an LDAP directory
43 def CheckLDAP(FingerPrint):
44    import ldap;
45    
46    # Connect to the ldap server
47    global ErrTyp, ErrMsg;
48    ErrType = EX_TEMPFAIL;
49    ErrMsg = "An error occured while performing the LDAP lookup:";
50    global l;
51    l = ldap.open(LDAPServer);
52    l.simple_bind_s("","");
53
54    # Search for the matching key fingerprint
55    Attrs = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + FingerPrint);
56    if len(Attrs) == 0:
57       raise Error, "Key not found"
58    if len(Attrs) != 1:
59       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
60
61    # See if the group membership is OK
62    if GroupMember != None:
63       Hit = 0;
64       for x in Attrs[0][1].get("supplementarygid",[]):
65          if x == GroupMember:
66            Hit = 1;
67       if Hit != 1:
68           raise Error, "You don't have %s group permissions."%(GroupMember);
69    
70 # Start of main program
71 # Process options
72 (options, arguments) = getopt.getopt(sys.argv[1:], "r:k:d:l:g:mp:");
73 for (switch, val) in options:
74    if (switch == '-r'):
75       ReplayCacheFile = val;
76    elif (switch == '-k'):
77       SetKeyrings(string.split(val,":"));
78    elif (switch == '-d'):
79       LDAPDn = val;
80    elif (switch == '-l'):
81       LDAPServer = val;
82    elif (switch == '-g'):
83       GroupMember = val;
84    elif (switch == '-m'):
85       AllowMIME = 0;
86    elif (switch == '-p'):
87       Phrases = val;
88       
89 Now = time.strftime("%a, %d %b %Y %H:%M:%S",time.gmtime(time.time()));
90 ErrMsg = "Indeterminate Error";
91 ErrType = EX_TEMPFAIL;
92 MsgID = None;
93 try:
94    # Startup the replay cache
95    ErrType = EX_TEMPFAIL;
96    if ReplayCacheFile != None:
97       ErrMsg = "Failed to initialize the replay cache:";
98       RC = ReplayCache(ReplayCacheFile);
99       RC.Clean();
100    
101    # Get the email 
102    ErrType = EX_PERMFAIL;
103    ErrMsg = "Failed to understand the email or find a signature:";
104    Email = mimetools.Message(sys.stdin,0);
105    MsgID = Email.getheader("Message-ID");
106    Msg = GetClearSig(Email,1);
107    if AllowMIME == 0 and Msg[1] != 0:
108       raise Error, "PGP/MIME disallowed";
109   
110    ErrMsg = "Message is not PGP signed:"
111    if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
112       raise Error, "No PGP signature";
113    
114    # Check the signature
115    ErrMsg = "Unable to check the signature or the signature was invalid:";
116    Res = GPGCheckSig(Msg[0]);
117    
118    if Res[0] != None:
119       raise Error, Res[0];
120       
121    if Res[3] == None:
122       raise Error, "Null signature text";
123
124    # Check the signature against the replay cache
125    if ReplayCacheFile != None:
126       ErrMsg = "The replay cache rejected your message. Check your clock!";
127       Rply = RC.Check(Res[1]);
128       if Rply != None:
129          raise Error, Rply;
130       RC.Add(Res[1]);
131
132    # Do LDAP stuff
133    if LDAPDn != None:
134       CheckLDAP(Res[2][1]);
135          
136    ErrMsg = "Verifying message:";
137    if Phrases != None:
138       F = open(Phrases,"r");
139       while 1:
140           Line = F.readline();
141           if Line == "": break;
142           if string.find(Res[3],string.strip(Line)) == -1:
143               raise Error,"Phrase '%s' was not found"%(string.strip(Line));
144       
145 except:
146    ErrMsg = "[%s] \"%s\" \"%s %s\"\n"%(Now,MsgID,ErrMsg,sys.exc_value);
147    sys.stderr.write(ErrMsg);
148    
149    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
150    List = traceback.extract_tb(sys.exc_traceback);
151    if len(List) >= 1:
152       Trace = Trace + "Python Stack Trace:\n";
153       for x in List:
154          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
155    #print Trace;
156    
157    sys.exit(EX_PERMFAIL);
158
159 # For Main   
160 sys.exit(0);