* Remove use of deprecated functions from the string module
[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 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    gidnumber_found = 0;
69    for key in Attrs[0][1].keys():
70       if (key == "gidNumber"):
71          gidnumber_found = 1
72
73    if (gidnumber_found != 1):
74       raise Error, "No gidnumber in attributes for fingerprint %s" % FingerPrint
75
76    # Look for the group with the gid of the user
77    GAttr = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"(&(objectClass=debianGroup)(gidnumber=%s))" % Attrs[0][1]["gidNumber"][0], ["gid"])
78    if len(GAttr) == 0:
79            raise Error, "Database inconsistency found: main group for account not found in database"
80
81    # See if the group membership is OK
82    # Only if a group was given on the commandline
83    if GroupMember != None:
84       Hit = 0;
85       # Check primary group first
86       if GAttr[0][1]["gid"][0] == GroupMember:
87          Hit = 1
88       else:
89           # Check supplementary groups
90           for x in Attrs[0][1].get("supplementaryGid",[]):
91               if x == GroupMember:
92                   Hit = 1;
93       if Hit != 1:
94           raise Error, "You don't have %s group permissions."%(GroupMember);
95    
96 # Start of main program
97 # Process options
98 (options, arguments) = getopt.getopt(sys.argv[1:], "r:k:d:l:g:mp:v");
99 for (switch, val) in options:
100    if (switch == '-r'):
101       ReplayCacheFile = val;
102    elif (switch == '-k'):
103       SetKeyrings(val.split(":"));
104    elif (switch == '-d'):
105       LDAPDn = val;
106    elif (switch == '-l'):
107       LDAPServer = val;
108    elif (switch == '-g'):
109       GroupMember = val;
110    elif (switch == '-m'):
111       AllowMIME = 0;
112    elif (switch == '-v'):
113       Verbose = 1;
114    elif (switch == '-p'):
115       Phrases = val;
116       
117 Now = time.strftime("%a, %d %b %Y %H:%M:%S",time.gmtime(time.time()));
118 ErrMsg = "Indeterminate Error";
119 ErrType = EX_TEMPFAIL;
120 MsgID = None;
121 try:
122    # Startup the replay cache
123    ErrType = EX_TEMPFAIL;
124    if ReplayCacheFile != None:
125       ErrMsg = "Failed to initialize the replay cache:";
126       RC = ReplayCache(ReplayCacheFile);
127       RC.Clean();
128    
129    # Get the email 
130    ErrType = EX_PERMFAIL;
131    ErrMsg = "Failed to understand the email or find a signature:";
132    Email = mimetools.Message(sys.stdin,0);
133    MsgID = Email.getheader("Message-ID");
134    print "Inspecting message %s"%MsgID;
135    verbmsg("Processing message %s" % MsgID)
136    Msg = GetClearSig(Email,1);
137    # print Msg
138    if AllowMIME == 0 and Msg[1] != 0:
139       raise Error, "PGP/MIME disallowed";
140   
141    ErrMsg = "Message is not PGP signed:"
142    if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1:
143       raise Error, "No PGP signature";
144    
145    # Check the signature
146    ErrMsg = "Unable to check the signature or the signature was invalid:";
147    Res = GPGCheckSig(Msg[0]);
148
149    if Res[0] != None:
150       raise Error, Res[0];
151       
152    if Res[3] == None:
153       raise Error, "Null signature text";
154
155    # Check the signature against the replay cache
156    if ReplayCacheFile != None:
157       ErrMsg = "The replay cache rejected your message. Check your clock!";
158       Rply = RC.Check(Res[1]);
159       if Rply != None:
160          raise Error, Rply;
161       RC.Add(Res[1]);
162       RC.close();
163
164    # Do LDAP stuff
165    if LDAPDn != None:
166       CheckLDAP(Res[2][1]);
167          
168    ErrMsg = "Verifying message:";
169    if Phrases != None:
170       F = open(Phrases,"r");
171       while 1:
172           Line = F.readline();
173           if Line == "": break;
174           if Res[3].find(Line.strip()) == -1:
175               raise Error,"Phrase '%s' was not found" % (Line.strip())
176       
177 except:
178    ErrMsg = "[%s] \"%s\" \"%s %s\"\n"%(Now,MsgID,ErrMsg,sys.exc_value);
179    sys.stderr.write(ErrMsg);
180    
181    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
182    List = traceback.extract_tb(sys.exc_traceback);
183    if len(List) >= 1:
184       Trace = Trace + "Python Stack Trace:\n";
185       for x in List:
186          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
187    #print Trace;
188    
189    sys.exit(EX_PERMFAIL);
190
191 # For Main   
192 print "Message %s passed"%MsgID;
193 sys.exit(0);