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