ud-mailgate: remove exception for münchen.debian.net
[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 Error = 'Message Error';
35
36 # Configuration
37 ReplayCacheFile = None;
38 LDAPDn = None;
39 LDAPServer = None;
40 GroupMember = None;
41 Phrases = None;
42 AllowMIME = 1;
43 Verbose = 0;
44
45 def verbmsg(msg):
46    if Verbose:
47       sys.stderr.write(msg + "\n")
48
49 # Match the key fingerprint against an LDAP directory
50 def CheckLDAP(FingerPrint):
51    import ldap;
52    import userdir_ldap;
53    
54    # Connect to the ldap server
55    global ErrTyp, ErrMsg;
56    ErrType = EX_TEMPFAIL;
57    ErrMsg = "An error occurred while performing the LDAP lookup:";
58    global l;
59    l = userdir_ldap.connectLDAP(LDAPServer);
60    l.simple_bind_s("","");
61
62    # Search for the matching key fingerprint
63    verbmsg("Processing fingerprint %s" % FingerPrint)
64    Attrs = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + FingerPrint);
65    if len(Attrs) == 0:
66       raise Error, "Key not found"
67    if len(Attrs) != 1:
68       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
69
70    gidnumber_found = 0;
71    for key in Attrs[0][1].keys():
72       if (key == "gidNumber"):
73          gidnumber_found = 1
74
75    if (gidnumber_found != 1):
76       raise Error, "No gidnumber in attributes for fingerprint %s" % FingerPrint
77
78    # Look for the group with the gid of the user
79    GAttr = l.search_s(LDAPDn,ldap.SCOPE_ONELEVEL,"(&(objectClass=debianGroup)(gidnumber=%s))" % Attrs[0][1]["gidNumber"][0], ["gid"])
80    if len(GAttr) == 0:
81            raise Error, "Database inconsistency found: main group for account not found in database"
82
83    # See if the group membership is OK
84    # Only if a group was given on the commandline
85    if GroupMember != None:
86       Hit = 0;
87       # Check primary group first
88       if GAttr[0][1]["gid"][0] == GroupMember:
89          Hit = 1
90       else:
91           # Check supplementary groups
92           for x in Attrs[0][1].get("supplementaryGid",[]):
93               if x == GroupMember:
94                   Hit = 1;
95       if Hit != 1:
96           raise Error, "You don't have %s group permissions."%(GroupMember);
97    
98 # Start of main program
99 # Process options
100 (options, arguments) = getopt.getopt(sys.argv[1:], "r:k:d:l:g:mp:v");
101 for (switch, val) in options:
102    if (switch == '-r'):
103       ReplayCacheFile = val;
104    elif (switch == '-k'):
105       SetKeyrings(val.split(":"));
106    elif (switch == '-d'):
107       LDAPDn = val;
108    elif (switch == '-l'):
109       LDAPServer = val;
110    elif (switch == '-g'):
111       GroupMember = val;
112    elif (switch == '-m'):
113       AllowMIME = 0;
114    elif (switch == '-v'):
115       Verbose = 1;
116    elif (switch == '-p'):
117       Phrases = val;
118       
119 Now = time.strftime("%a, %d %b %Y %H:%M:%S",time.gmtime(time.time()));
120 ErrMsg = "Indeterminate Error";
121 ErrType = EX_TEMPFAIL;
122 MsgID = None;
123 try:
124    # Startup the replay cache
125    ErrType = EX_TEMPFAIL;
126    if ReplayCacheFile != None:
127       ErrMsg = "Failed to initialize the replay cache:";
128       RC = ReplayCache(ReplayCacheFile);
129
130    # Get the email 
131    ErrType = EX_PERMFAIL;
132    ErrMsg = "Failed to understand the email or find a signature:";
133    mail = email.parser.Parser().parse(sys.stdin);
134    MsgID = mail["Message-ID"]
135
136    print "Inspecting message %s"%MsgID;
137    verbmsg("Processing message %s" % MsgID)
138    Msg = GetClearSig(mail,1);
139    if AllowMIME == 0 and Msg[1] != 0:
140       raise Error, "PGP/MIME disallowed";
141   
142    ErrMsg = "Message is not PGP signed:"
143    if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1:
144       raise Error, "No PGP signature";
145    
146    # Check the signature
147    ErrMsg = "Unable to check the signature or the signature was invalid:";
148    pgp = GPGCheckSig2(Msg[0])
149
150    if not pgp.ok:
151       raise UDFormatError, pgp.why
152    if pgp.text is None:
153       raise UDFormatError, "Null signature text"
154
155    # Check the signature against the replay cache
156    if ReplayCacheFile != None:
157       RC.process(pgp.sig_info)
158
159    # Do LDAP stuff
160    if LDAPDn != None:
161       CheckLDAP(pgp.key_fpr)
162
163    ErrMsg = "Verifying message:";
164    if Phrases != None:
165       F = open(Phrases,"r");
166       while 1:
167           Line = F.readline();
168           if Line == "": break;
169           if pgp.text.find(Line.strip()) == -1:
170               raise Error,"Phrase '%s' was not found" % (Line.strip())
171       
172 except:
173    ErrMsg = "[%s] \"%s\" \"%s %s\"\n"%(Now,MsgID,ErrMsg,sys.exc_value);
174    sys.stderr.write(ErrMsg);
175    
176    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
177    List = traceback.extract_tb(sys.exc_traceback);
178    if len(List) >= 1:
179       Trace = Trace + "Python Stack Trace:\n";
180       for x in List:
181          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
182    #print Trace;
183    
184    sys.exit(EX_PERMFAIL);
185
186 # For Main   
187 print "Message %s passed"%MsgID;
188 sys.exit(0);