-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclsmime
More file actions
executable file
·1631 lines (1431 loc) · 61.3 KB
/
clsmime
File metadata and controls
executable file
·1631 lines (1431 loc) · 61.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
"""
* File: clsmime
* Version : 1.2
* License : BSD-3-Clause
*
* Copyright (c) 2023 - 2026
* Ralf Senderek, Ireland. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Ralf Senderek.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
"""
import sys, os, re
from binascii import *
ERR_CL = -1
OK = 0
ERR_USE = 1
ERR_PERM = 2
ERR_PASSWORD = 3
ERR_INSTALL = 4
ERR_WRONGKEY = 5
ERR_DECODE = 6
ERR_SIZE = 7
ERR_ENCRYPT = 8
ERR_DECRYPT = 9
ERR_CORRUPT = 10
ERR_INCOMPLETE = 11
ERR_INPUT = 12
ERR_SIGN = 13
ERR_VERIFY = 14
ERR_BADSIG = 15
DEBUG = False
BINARY = False
INTEGRITYCHECK = False
DETACHEDSIGNATURE = False
CERTIMPORTED = False
SAVECHAIN = False
Mode = "encrypt"
MessageType = "text"
MinPasswordLength = 8
MaxPasswordLength = 64
Version = "1.2"
KeyFileName = ""
FileName = ""
CertFileName = ""
InputBytes = ""
MaxBytes = 268400000 # no more than INT_MAX//8 (pow(2,31)//8)
MaxBufferSize = MaxBytes + 32768
Data = bytearray()
KeyFile = bytearray()
ImportCert = bytearray()
Password = bytearray()
Text = bytearray()
isMultipart = False
HeaderLength = 28
NumLines = 1000
try:
from cryptlib_py import *
except:
ERR_IMPORT = """
The python3 library is not installed. You need to install the packages cryptlib-python3 and cryptlib.
You will find them for a variety of operating systems here:
https://senderek.ie/cryptlib
or in the Fedora repository.
"""
print( ERR_IMPORT )
exit( ERR_INSTALL )
ASKPASS = "/bin/systemd-ask-password"
if not os.path.isfile(ASKPASS) :
print ("Error: Please install " + ASKPASS + " to ensure safe password input")
exit(ERR_INSTALL)
#-------------------------------------------------#
def print_help():
Help = """
clsmime encrypts or verifies message data with a RSA public key stored in a certificate file.
clsmime decrypts or signs data with a RSA private key stored in a *.p15 keyset file.
usage: clsmime [OPTIONS] encrypt MessageFile Certificate
clsmime [OPTIONS] decrypt EncryptedMessage KeySetFile
clsmime [OPTIONS] sign MessageFile KeySetFile
clsmime [OPTIONS] verify SignedMessage [CArootCertificate]
clsmime list [<num>] MessageFile
clsmime OPTIONS
The input size is limited to 150 MByte.
OPTIONS are:
-debug print debugging information to stderr
-detach generate a detached signature in S/MIME format as multipart/signed
(default is a signature containing the text)
-binary do not change anything (default is text mode)
in text mode all \\n are replaced by \\r\\n and a header is added to the input bytes
-integritycheck
forces integrity protection while encrypting data
the cryptogram is enveloped in a authEnvelopedData object that cannot be decrypted
with OpenSSL
-help display this message
-version display version information
-certchain write the certchain to the file system while verification of signatures
Full documentation <https://senderek.ie/cryptlib/tools>
INTEROPERABILITY
S/MIME capable E-mail clients (Thunderbird, Evolution, Outlook)
Thunderbird: Import the CA certificate (into the CA section) before you import a user's certificate
(into the person section).
Evolution : Import the CA certificate (into the CA section) before you import a user's certificate
(into the person section).
MS Outlook: Use the contacts tab to enter the Common Name and the email address and finally
click on the 'certificate button' to import the contact's certificate stored in a
*.cer file.
OpenSSL
The following OpenSSL commands can be used to exchange message files with clsmime :
Encryption : openssl smime -encrypt -aes-256-cbc -in message -binary -out message.smime certfile
Decryption : openssl smime -decrypt -in message -out message.clear -recip cert -inkey RSAkey
Signing : openssl smime -sign -in message -text -signer cert -inkey RSAkey -out message.sig
Verification : openssl smime -verify -in message -out message.verified -inkey certfile -CAfile CAcertfile
"""
print( Help )
#-----------------------------------------------------------#
def print_debug ( message ):
if DEBUG and message :
sys.stderr.write( "Debug: " )
sys.stderr.write( message + "\n" )
#-----------------------------------------------------------#
def safe_input(message):
try:
return input(message)
except:
print()
return ""
#-----------------------------------------------------------#
def get_proper_filename():
global OutFilename
# stdin is not a source of data !
if ( Mode == "encrypt" ) :
OutFilename = FileName + ".smime"
if (os.path.isfile(OutFilename)) :
RET = safe_input("Overwrite " + OutFilename + " ? [y/n] ")
if (RET != "y") :
OutFilename = safe_input("File name to write : ")
elif ( Mode == "decrypt" ) :
if (FileName[-6:] == ".smime") :
OutFilename = FileName[:-6]
else:
# get a proper file name to write to
OutFilename = safe_input("File name to write : ")
if (os.path.isfile(OutFilename)) :
RET = safe_input("Overwrite " + OutFilename + " ? [y/n] ")
if (RET != "y") :
OutFilename = safe_input("Filename to write : ")
elif ( Mode == "sign" ) :
OutFilename = FileName + ".sig"
if (os.path.isfile(OutFilename)) :
RET = safe_input("Overwrite " + OutFilename + " ? [y/n] ")
if (RET != "y") :
OutFilename = safe_input("File name to write : ")
if ( Mode == "verify" ) :
OutFilename = FileName + ".verified"
if (os.path.isfile(OutFilename)) :
RET = safe_input("Overwrite " + OutFilename + " ? [y/n] ")
if (RET != "y") :
OutFilename = safe_input("File name to write : ")
OutFilename = sanitize(OutFilename)
if len(OutFilename) == 0 :
print("Please enter a valid file name")
exit(ERR_PERM)
#-----------------------------------------------------------#
def analyze_SMIME_signature( input ):
# this is used by verify only
global Text
global isMultipart
global BINARY
# check if input is multipart
start = input.find(b'multipart', 0)
if start != -1 :
isMultipart = True
# process the multipart header
nl = 1
if ( 13 in input[start:start + 200]) :
nl = 2
# find the border string
border = bytearray()
B = bytearray(b'boundary=')
start = input.find(B)
if start != -1:
start = start + len(B) + 1
i = start
# read until " is found
while (i < len (input)-1) :
if (input[i] == 34) :
end = i
break
i = i + 1
if ((end-start) > 100) :
# no valid border detected
print_debug("no valid border detected")
return bytearray()
border = input[start:end]
print_debug( "Border = "+ str(border.decode()) )
# read NL
start = end + 2*nl + 1
# read border ( = end of description )
end = input.find(border, start)
# extract the description
Description = bytearray()
if end == -1:
# no description
Description = bytearray()
else:
# remove additional -- if present
end -= 1
i = end
while (i < len (input)-1) :
if input[i] == 45:
end -= 1
else:
break
i -= 1
Description = input[start:end - 2*nl + 1]
print_debug("Descr: " + str(Description.decode()))
start = end + len(border) + nl + 3
textstart = start
headerstart = start
# check which line-end is being used in the text
nl = 1
if ( 13 in input[start:start+200]) :
nl = 2
# read next border ( = end of text including header)
end = input.find(border, start)
# remove -- if present
end -= 1
i = end
while (i < len (input)-1) :
if input[i] == 45:
end -= 1
else:
break
i -= 1
# the final newline after the text is NOT always \r\n
textend = end - 1
if input[textend] == 13 :
textend -= 1
Text = input[textstart:textend+1]
if DEBUG:
DOUBLENL = bytearray()
if ( 13 in Text ) :
DOUBLENL.append(13)
DOUBLENL.append(10)
DOUBLENL.append(13)
DOUBLENL.append(10)
else:
DOUBLENL.append(10)
DOUBLENL.append(10)
HeaderLength = Text.find(DOUBLENL, 0)
if HeaderLength == -1:
HeaderLength = 0
else:
HeaderLength += 2*nl
print_debug("HeaderLength: " + str(HeaderLength))
print_debug("Text Header : " + str(Text[:HeaderLength]))
print_debug("Text : " + str(Text[:300]))
# analyze block after text border
start = textend + len(border) + 2*nl + 1
# find "\r\n\r\nMI" or "\n\nMI"
i = start
while (i < len (input)-1) :
if ((input[i-4] == 13) and (input[i-3] == 10) and (input[i-2] == 13) and (input[i-1] == 10) and (input[i] == 77) and (input[i+1] == 73)) :
break
elif ((input[i-2] == 10) and (input[i-1] == 10) and (input[i] == 77) and (input[i+1] == 73)) :
break
i = i + 1
startblock = i
endblock = input.find(border, startblock)
if endblock == -1:
# no block
EncodedBlock = bytearray()
else:
# remove -- if present
i = endblock
while (i < len (input)-1) :
if input[i] == 45:
endblock -= 1
else:
break
i -= 1
# remove NL
endblock = endblock - nl + 1
EncodedBlock = input[startblock:endblock]
print_debug("last part of encoded block : " + str(EncodedBlock[-20:].decode()))
# check if Text has \r\n
if not (13 in Text):
print_debug("replacing all '\\n' with '\\r\\n' in the text block")
# replace all \n with \r\n
New = bytearray()
i = 0
while (i < len(Text)) :
if (Text[i] == 10) :
New.append(13)
New.append(10)
else:
New.append(Text[i])
i += 1
Text = New
BINARY = False
return EncodedBlock
else:
# single signature block or binary input
isMultipart = False
Text = bytearray()
start = 0
# find "\r\n\r\nMI" or "\n\nMI"
i = 4
while (i < len (input)-1) :
if ((input[i-4] == 13) and (input[i-3] == 10) and (input[i-2] == 13) and (input[i-1] == 10) and (input[i] == 77) and (input[i+1] == 73)) :
break
elif ((input[i-2] == 10) and (input[i-1] == 10) and (input[i] == 77) and (input[i+1] == 73)) :
break
i = i + 1
startblock = i
if (i == len(input)-1) and (start == 0):
BINARY = True
return input
BINARY = False
return input[startblock:-1]
#-----------------------------------------------#
def write_raw_message(buff, pathname):
# writes an encrypted bytearray into a file
print("Writing " + str(len(buff)) + " bytes to " + pathname )
pathname = sanitize(pathname)
if len(pathname) == 0:
print("Error: Illegal file name.")
return False
try:
F = open(pathname,'wb')
F.write(buff)
F.close()
unix("chmod 600 " + pathname)
return True
except:
print (str( sys.exc_info()[0]) )
print ("Error: cannot write to " + pathname)
clean_envelope()
exit(ERR_PERM)
#-----------------------------------------------------------#
def remove_header(buff) :
# removes \r and then the header "Content-Type ..."
DOUBLENL = bytearray()
if ( 13 in buff) :
DOUBLENL.append(13)
DOUBLENL.append(10)
DOUBLENL.append(13)
DOUBLENL.append(10)
else:
DOUBLENL.append(10)
DOUBLENL.append(10)
HeaderLength = buff.find(DOUBLENL, 0)
if HeaderLength == -1:
HeaderLength = 0
else:
HeaderLength += len(DOUBLENL)
NewText = bytearray()
if (len(buff) > HeaderLength):
i = HeaderLength
while (i < len(buff)) :
if (buff[i] != 13) :
NewText.append(buff[i])
i += 1
return NewText
#-----------------------------------------------------------#
def unix (command) :
Result = ""
if os.name == "posix" :
try:
Pipe = os.popen(sanitize(command), "r")
Result = Pipe.read()
Pipe.close()
return Result
except:
print("\nA Unix command failed!\n")
return Result
#-----------------------------------------------------------#
def get_random_bytes ( num ):
# this function does not need to produce cryptographically secure random numbers
try:
from random import randbytes
return randbytes( num )
except:
RandomBuffer = bytearray(b' '*num)
RandomContext_object = cryptCreateContext( cryptUser, CRYPT_ALGO_AES )
RandomContext = int( RandomContext_object )
cryptSetAttribute( RandomContext, CRYPT_CTXINFO_MODE, CRYPT_MODE_CFB )
cryptGenerateKey( RandomContext )
cryptEncrypt( RandomContext, RandomBuffer )
cryptDestroyContext( RandomContext )
return RandomBuffer
#-----------------------------------------------------------#
def clean_envelope():
global Envelope
global cryptKeyset
global certificate
global sigKeyContext
global Password
print_debug("Cleaning envelope before exit")
try:
if (Mode == "decrypt") or (Mode == "sign") :
Password = get_random_bytes( len(Password) )
cryptKeysetClose( cryptKeyset )
if (Mode == "sign") :
cryptDestroyContext( sigKeyContext )
elif (Mode == "encrypt"):
cryptDestroyContext( certificate )
except:
pass
cryptDestroyEnvelope( Envelope )
cryptEnd()
#-----------------------------------------------------------#
def sanitize(data):
forbidden = "!\"§&$%()[]{}=?*;,<>\\"
good = ""
for i in range(len(data)) :
if (data[i] not in forbidden) and (ord(data[i]) < 128):
good += data[i]
return good
#-----------------------------------------------------------#
def analyze_SMIME_data( input ):
global BINARY
if not input:
return b''
start = 0
# find '\nMI'
BEGIN = bytearray(b'\nMI')
pos = input.find(BEGIN, start)
if pos == -1 :
# maybe there is no \n in front of MI
if (input[0] == 77) and (input[1] == 73):
# could also be MIME-Version
if (input[2] == 77) and (input[3] == 69) and (input[4] == 45):
print_debug("found MIME- at pos " + str(0))
start = 5
pos = input.find(BEGIN, start)
if pos != -1:
print_debug("found MI-block " + str(pos +1))
BINARY = False
start = pos + 1
else:
# input maybe binary data
BINARY = True
else:
# could also be MIME-Version
i = pos + 1
if (input[i+2] == 77) and (input[i+3] == 69) and (input[i+4] == 45):
print_debug("Found MIME- at " + str(i))
start = pos + 5
pos = input.find(BEGIN, start)
if pos != -1:
BINARY = False
start = pos + 1
else:
BINARY = False
start = pos + 1
if BINARY:
ASCII = input
else:
ASCII = input[start:-1]
return ASCII
#-----------------------------------------------------------#
def write_smime_message(buff, pathname):
# writes an encrypted bytearray into a file
pathname = sanitize(pathname)
if len(pathname) == 0:
print("Error: Illegal file name.")
return False
try:
F = open(pathname,'w')
F.write("MIME-Version: 1.0\n")
F.write("Content-Disposition: attachment; filename=smime.p7m\n")
F.write("Content-Type: application/x-pkcs7-mime; smime-type=enveloped-data; name=smime.p7m\n")
F.write("Content-Transfer-Encoding: base64\n")
F.write("Content-Description: Data encrypted with clSMIME " + Version + "\n\n")
F.write("\n")
ASCII = b2a_base64(buff)
i = 0
while i < len(ASCII) :
line = ASCII[i:i+64]
i = i + 64
F.write(line.decode())
if i < len(ASCII) :
F.write("\n")
F.write("\n")
F.write("\n")
unix("chmod 600 " + pathname)
return True
except:
print (str( sys.exc_info()[0]) )
print ("Error: cannot write to " + pathname)
clean_envelope()
exit(ERR_PERM)
#-----------------------------------------------------------#
def write_pure_signature(buff, pathname):
# writes a signed bytearray into a file
pathname = sanitize(pathname)
if len(pathname) == 0:
print("Error: Illegal file name.")
return False
try:
F = open(pathname,'w')
F.write("MIME-Version: 1.0\n")
F.write("Content-Disposition: attachment; filename=smime.p7s\n")
F.write("Content-Type: application/x-pkcs7-mime; smime-type=enveloped-data; name=smime.p7s\n")
F.write("Content-Transfer-Encoding: base64\n")
F.write("Content-Description: Data signed with clSMIME " + Version + "\n\n")
F.write("\n")
ASCII = b2a_base64(buff)
ASCII = ASCII[:-1]
i = 0
while i < len(ASCII) :
line = ASCII[i:i+64]
i = i + 64
F.write(line.decode())
if i < len(ASCII) :
F.write("\n")
F.write("\n")
unix("chmod 600 " + pathname)
return True
except:
print (str( sys.exc_info()[0]) )
print ("Error: cannot write to " + pathname)
clean_envelope()
exit(ERR_PERM)
#-----------------------------------------------------------#
def write_smime_signature(text, buff, pathname):
# writes a signed bytearray into a file
# generate a random boundary
pathname = sanitize(pathname)
if len(pathname) == 0:
print("Error: Illegal file name.")
return False
B = bytearray()
B = get_random_bytes(16)
Boundary = "----" + hexlify( B ).decode()
try:
F = open(pathname,'w')
F.write("MIME-Version: 1.0\n")
F.write("Content-Type: multipart/signed; protocol=\"application/x-pkcs7-signature\"; micalg=\"sha-256\"; boundary=\"")
F.write(Boundary)
F.write("\"\n")
F.write("\nThis is an S/MIME signed message\n\n")
F.write("--" + Boundary)
F.write("\n")
# add the text with header
New = bytearray()
for x in text:
New.append(x)
F.write(New.decode())
F.write("\r\n")
F.write("--" + Boundary)
F.write("\n")
F.write("Content-Type: application/x-pkcs7-signature; name=\"smime.p7s\"\n")
F.write("Content-Transfer-Encoding: base64\n")
F.write("Content-Disposition: attachment; filename=\"smime.p7s\"\n")
F.write("Content-Description: Data signed with clSMIME " + Version + "\n\n")
F.write("\n")
ASCII = b2a_base64(buff)
ASCII = ASCII[:-1]
i = 0
while i < len(ASCII) :
line = ASCII[i:i+64]
i = i + 64
F.write(line.decode())
if i < len(ASCII) :
F.write("\n")
F.write("\n")
F.write("\n")
F.write("--" + Boundary)
F.write("\n")
F.write("\n")
unix("chmod 600 " + pathname)
return True
except:
print (str( sys.exc_info()[0]) )
print ("Error: cannot write to " + pathname)
clean_envelope()
exit(ERR_PERM)
#-----------------------------------------------------------#
def readCertificateFromFile( FileName, Header ):
global BINARY
Header = Header + "-----"
F = open( FileName, "rb" )
data = F.read()
F.close()
start = end = 0
BEGIN = bytearray(b'-----BEGIN ')
BEGIN.extend(Header.encode())
END = bytearray(b'-----END ')
END.extend(Header.encode())
begin = False
Length = len( data )
ASCII = bytearray()
i = j = 0
while ( (not begin) and (i < Length) ) :
while ((i < Length) and (data[i] != 45)) :
i = i + 1
if (i < Length) :
begin = True
# hit first -
j = 0
while ((j < (len(BEGIN) -1)) and begin and (i < Length)) :
if (data[i] != BEGIN[j]) :
begin = False
i = i + 1
j = j + 1
if (begin) :
start = i - len(BEGIN) + 1
# find -----END CERTIFICATE----- or -----END CERTIFICATE REQUEST-----
begin = False
while ( (not begin) and (i < Length) ) :
while ((i < Length) and (data[i] != 45)) :
i = i + 1
if (i < Length) :
begin = True
# hit first -
j = 0
while ((j < (len(END) )) and begin and (i < Length)) :
if (data[i] != END[j]) :
begin = False
i = i + 1
j = j + 1
if (begin) :
end = i
# copy start to end to ASCII block
i = start
j = 0
while (i < end) :
ASCII.append( data[i] )
j = j + 1
i = i + 1
BINARY = False
if ( (start == 0) and (end == 0) ) :
# data is probably binary input string
BINARY = True
i = start
j = 0
while (i < len(data)) :
ASCII.append( data[i] )
j = j + 1
i = i + 1
return ASCII
#-----------------------------------------------------------#
def SignatureIsOK(vbuf, vtext):
Test_Envelope_object = cryptCreateEnvelope( cryptUser, CRYPT_FORMAT_AUTO)
TestEnvelope = int (Test_Envelope_object)
if ( vbuf ) :
try:
print_debug("Checking the new signature bytes")
bytesCopied = cryptPushData( TestEnvelope, vbuf)
cryptFlushData( TestEnvelope )
if DETACHEDSIGNATURE :
# push the text into envelope
bytesCopied = cryptPushData( TestEnvelope, vtext)
cryptFlushData( TestEnvelope )
else:
vClear = bytearray( b' ' * MaxBytes )
Num = cryptPopData( TestEnvelope, vClear, MaxBytes )
vResult = -99
vResult = cryptGetAttribute( TestEnvelope, CRYPT_ENVINFO_SIGNATURE_RESULT)
if vResult == 0 :
print_debug("The signature is OK.")
cryptDestroyEnvelope( TestEnvelope )
print_debug("Signature check successful")
return True
except:
cryptDestroyEnvelope( TestEnvelope )
return False
cryptDestroyEnvelope( TestEnvelope )
return False
#-----------------------------------------------------------#
if ( len(sys.argv) > 1 ):
# legitimate options or a file name is in the parameter list
if "-debug" in sys.argv :
DEBUG = True
sys.argv.remove( "-debug" )
if "-help" in sys.argv :
print_help()
exit( OK )
if "-version" in sys.argv :
print ( Version )
exit( OK )
if "-detach" in sys.argv :
DETACHEDSIGNATURE = True
sys.argv.remove( "-detach" )
if "-binary" in sys.argv :
BINARY = True
MessageType = "binary"
sys.argv.remove( "-binary" )
if "-integritycheck" in sys.argv :
INTEGRITYCHECK = True
sys.argv.remove( "-integritycheck" )
if ("-certchain" in sys.argv):
SAVECHAIN = True
sys.argv.remove( "-certchain" )
if ("-chain" in sys.argv):
SAVECHAIN = True
sys.argv.remove( "-chain" )
if ( len(sys.argv) >= 2 ):
if sys.argv[1] == "list" :
Mode = "list"
if len(sys.argv) > 2 :
# read number of lines to be displayed
try:
NumLines = abs( int(sys.argv[2]) )
del(sys.argv[2])
except:
pass
if ( len(sys.argv) >= 2 ):
# legitimate options are in the parameter list
if "encrypt" in sys.argv :
Mode = "encrypt"
sys.argv.remove( "encrypt" )
elif "decrypt" in sys.argv :
Mode = "decrypt"
sys.argv.remove( "decrypt" )
elif "sign" in sys.argv :
Mode = "sign"
sys.argv.remove( "sign" )
elif "verify" in sys.argv :
Mode = "verify"
sys.argv.remove( "verify" )
elif "list" in sys.argv :
Mode = "list"
sys.argv.remove( "list" )
else:
print("You need to specify an operation: encrypt or decrypt or sign or verify or list")
exit( ERR_USE )
else:
print("usage: clsmime encrypt MessageFile certificate")
print(" clsmine decrypt EncryptedMessage KeysetName")
print(" clsmime sign MessageFile KeysetName")
print(" clsmime verify SignedMessage [CArootCert]")
print(" clsmime list [<NumLines>] MessageFile")
exit(ERR_USE)
# all modes are processed
# read the message file
if len(sys.argv) >= 2 :
if os.path.isfile(sys.argv[1]) :
FileName = sanitize( sys.argv[1] )
try:
F = open( FileName, "rb" )
InputBytes = F.read( MaxBytes )
F.close()
except:
print( "Cannot open file " + str(FileName) )
exit ( ERR_PERM )
else:
print ("No such file: " + sys.argv[1] )
exit ( ERR_INPUT )
sys.argv.remove( sys.argv[1] )
if len(sys.argv) >= 2 :
if (Mode == "decrypt") or (Mode == "sign") :
SafeKeysetName = sanitize( sys.argv[1] )
if len( SafeKeysetName) < 2 :
print("The keyset name is invalid.")
exit( ERR_USE )
if SafeKeysetName[-4:] == ".p15" :
KeyFileName = SafeKeysetName
else:
KeyFileName = SafeKeysetName + ".p15"
# check if keyset file exists
if os.path.isfile (KeyFileName):
if os.path.getsize(KeyFileName) < 100 :
print( "There is a keyset named " + KeyFileName +" but it is not a valid keyset file." )
print( "Please use generate to create a new keyset or use a different name." )
exit( ERR_CORRUPT )
else:
# decrypt and sign need an existing keyset
print( "There is no keyset named " + KeyFileName )
exit( ERR_USE )
KeyFile.extend( KeyFileName.encode() )
if (Mode == "encrypt"):
# read the recipient's certificate
CertFileName = sanitize( sys.argv[1] )
try:
ImportCert = readCertificateFromFile(CertFileName, "CERTIFICATE")
CERTIMPORTED = True
except:
print( "Cannot read the certificate " + CertFileName + "." )
exit( ERR_PERM )
elif (Mode != "verify") and (Mode != "list"):
print("usage: clsmime encrypt MessageFile certificate")
print(" clsmine decrypt EncryptedMessage KeysetName")
print(" clsmime sign MessageFile KeysetName")
print(" clsmime verify SignedMessage [CArootCert]")
print(" clsmime list [<NumLines>] MessageFile")
exit(ERR_USE)
if (Mode == "verify") and (len(sys.argv) >= 2):
# read the CA's certificate, if one is given
CertFileName = sanitize( sys.argv[1] )
try:
ImportCert = readCertificateFromFile(CertFileName, "CERTIFICATE")
CERTIMPORTED = True
except:
print( "Cannot read the certificate " + CertFileName + "." )
exit( ERR_PERM )
OutFilename = FileName
get_proper_filename ()
##### Begin Cryptlib code #####
try:
cryptInit()
cryptUser = CRYPT_UNUSED
# collect randomness information
cryptAddRandom( CRYPT_RANDOM_SLOWPOLL )
# get Cryptlib Version
Major = cryptGetAttribute(CRYPT_UNUSED, CRYPT_OPTION_INFO_MAJORVERSION)
Minor = cryptGetAttribute(CRYPT_UNUSED, CRYPT_OPTION_INFO_MINORVERSION)
Step = cryptGetAttribute(CRYPT_UNUSED, CRYPT_OPTION_INFO_STEPPING)
CryptlibVersion = str(Major)+"."+str(Minor)+"."+str(Step)
print( "clSMIME " + Version + " uses Cryptlib " + CryptlibVersion + "\n")
if DEBUG:
print_debug("Outfile = " + OutFilename)
if len(KeyFileName) > 0:
print_debug("Keyfile = " + KeyFileName)
if len(ImportCert) > 0 :
try:
print_debug("ImportCert = \n" + str(ImportCert[:40].decode()) + " ... " + str(ImportCert[-40:].decode()) + " length: " + str(len(ImportCert)) + " bytes." )
except:
pass
if (Mode == "decrypt") or (Mode == "verify") :
Envelope_object = cryptCreateEnvelope( cryptUser, CRYPT_FORMAT_AUTO)
else:
Envelope_object = cryptCreateEnvelope( cryptUser, CRYPT_FORMAT_SMIME )
try:
Envelope = int( Envelope_object )
except:
print ("Cryptlib error.")
cryptDestroyEnvelope( Envelope )
cryptEnd()
exit (ERR_CL)
#-------LIST----------#
if Mode == "list":
import subprocess
if NumLines < 1000 :
Num = str(NumLines)
else:
Num = "all"
print ("Listing the ASN1 structure of " + FileName + " (" + Num + " lines)\n")
if InputBytes:
Data.extend( InputBytes )
Data = analyze_SMIME_data( Data )
# base64 decode ASCII
Buffer = bytearray()
if not BINARY:
try:
print_debug("Data : " + str(Data[:20].decode()) + " ... " + str(Data[-20:].decode()) + " length : " + str(len(Data)) + " bytes.")
bytestring = a2b_base64( Data )
Buffer.extend(bytestring)
except:
print ( "Error: cannot decode message block" )
clean_envelope()
exit (ERR_DECODE)
else:
# nothing to decode
Buffer = Data
# write Buffer into a temporary file
from pathlib import Path
TempFile = str(Path.home()) + "/.cryptlibtempfile"
try:
F = open (TempFile, "wb")
F.write(Buffer)
F.close()
unix("/bin/chmod 600 " + TempFile )
except:
print("Error: Cannot write to temporary file " + TempFile)
clean_envelope()
exit ( ERR_PERM )