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