-
Notifications
You must be signed in to change notification settings - Fork 4
/
x509-mode.el
1682 lines (1494 loc) · 60.7 KB
/
x509-mode.el
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
;;; x509-mode.el --- View certificates, CRLs and keys using OpenSSL -*- lexical-binding:t; coding:utf-8 -*-
;; Copyright (C) 2017-2023 Fredrik Axelsson <[email protected]>
;; Author: Fredrik Axelsson <[email protected]>
;; Homepage: https://github.com/jobbflykt/x509-mode
;; Package-Requires: ((emacs "25.1") (compat "29.1.4.2"))
;; This file is not part of GNU Emacs.
;; MIT License
;;
;; Copyright (C) 2017-2023 Fredrik Axelsson <[email protected]>
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to
;; deal in the Software without restriction, including without limitation the
;; rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
;; sell copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
;; FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
;; IN THE SOFTWARE.
;;; Commentary:
;; Major mode for viewing certificates, CRLs, and other PKI-related files.
;;
;; Uses OpenSSL for viewing PEM and DER encoded PKI entities.
;;
;; Prerequisites: OpenSSL. Customize the variable `x509-openssl-cmd' to name
;; the openssl binary. Defaults are "openssl" on Linux (assuming it's on PATH)
;; and "C:/Program Files/Git/mingw64/bin/openssl.exe" on Windows (assuming Git
;; for Windows is installed in its default location).
;;
;; Usage: Open a file containing a certificate, either PEM or DER encode. Now
;; use M-x `x509-viewcert' to create a new buffer that displays the decoded
;; certificate. Use `x509-viewcrl', `x509-viewasn1',`x509-viewkey',
;; `x509-viewpublickey', `x509-viewdh', `x509-viewreq', `x509-viewpkcs7' in a
;; similar manner.
;;
;; M-x `x509-dwim' tries to guess what view-function to call. It falls back to
;; `x509-viewasn1' if it fails.
;;
;; If point is at the beginning of, or in, a PEM region, all view functions,
;; including `x509-dwim', tries extra hard to use that region as input. This
;; often works even when there is other data ahead and after region and if the
;; region is indented or the lines are quoted.
;;
;; Use C-u prefix with any command for editing the command arguments.
;;
;; When in a x509 buffer, use keys `e' and `t' to edit current command or
;; toggle between x509-asn1-mode and x509-mode respectively.
;;
;; In `x509-asn1-mode', keys `d' and `s' does asn1parse -offset (mnemonic
;; "down")
;; or -strparse. `u' undoes the last `d' or `s'.
;;
;; Also in `x509-asn1-mode', key `x' displays a buffer in `hexl-mode' that
;; follows the current line in the asn1 buffer. Inspired by `rmsbolt-mode'.
;;; Code:
(require 'cl-lib)
(require 'compat)
(defgroup x509 nil
"View certificates, CRLs, keys and other related files using OpenSSL."
:group 'extensions
:group 'convenience
:link '(emacs-library-link :tag "Lisp File" "x509-mode.el"))
(defcustom x509-openssl-cmd
(if (eq system-type 'windows-nt)
"C:/Program Files/Git/mingw64/bin/openssl.exe"
"openssl")
"Path to OpenSSL binary.
Example:
\"/usr/bin/openssl\" or just \"openssl\" on Linux
\"C:/Program Files/Git/mingw64/bin/openssl\" on Windows."
:type 'string
:group 'x509)
(defcustom x509-x509-default-arg
"x509 -text -noout -nameopt utf8 -nameopt multiline"
"Default arguments for \"openssl x509\" command."
:type 'string
:group 'x509)
(defcustom x509-req-default-arg
"req -text -noout -nameopt utf8 -nameopt multiline"
"Default arguments for \"openssl req\" command."
:type 'string
:group 'x509)
(defcustom x509-crl-default-arg
"crl -text -noout -nameopt utf8 -nameopt multiline"
"Default arguments for \"openssl crl\" command."
:type 'string
:group 'x509)
(defcustom x509-pkcs7-default-arg "pkcs7 -noout -text -print_certs"
"Default arguments for \"openssl pkcs7\" command."
:type 'string
:group 'x509)
(defcustom x509-dhparam-default-arg "dhparam -text -noout"
"Default arguments for \"openssl dhparam\" command."
:type 'string
:group 'x509)
(defcustom x509-ecparam-default-arg "ecparam -text -noout"
"Default arguments for \"openssl ecparam\" command."
:type 'string
:group 'x509)
(defcustom x509-pkey-default-arg "pkey -text -noout"
"Default arguments for \"openssl pkey\" command."
:type 'string
:group 'x509)
(defcustom x509-pkey-pubin-default-arg "pkey -text -noout -pubin"
"Default arguments for \"openssl pkey -pubin\" command."
:type 'string
:group 'x509)
(defcustom x509-asn1parse-default-arg "asn1parse"
"Default arguments for \"openssl asn1parse\" command."
:type 'string
:group 'x509)
(defgroup x509-faces nil
"Faces used by x509."
:group 'x509
:group 'faces)
(defface x509-keyword-face '((t (:inherit font-lock-builtin-face)))
"Face for keywords."
:group 'x509-faces)
(defface x509-constant-face '((t (:inherit font-lock-constant-face)))
"Face for constants."
:group 'x509-faces)
(defface x509-short-name-face '((t (:bold t)))
"Face for short names, e.g, CN and OU."
:group 'x509-faces)
(defface x509-string-face '((t (:inherit font-lock-string-face)))
"Face for strings."
:group 'x509-faces)
(defface x509-hex-string-face '((t (:inherit font-lock-comment-face)))
"Face for colon-separated hex values."
:group 'x509-faces)
(defface x509-oid-link-face '((t (:inherit (link font-lock-constant-face))))
"Face for OID buttons."
:group 'x509-faces)
(defface x509-oid-face '((t (:inherit font-lock-constant-face)))
"Face for symbolic, known, OIDs."
:group 'x509-faces)
(defface x509-asn1-sequence-face
'((t (:inherit font-lock-regexp-grouping-backslash)))
"Face for ASN.1 sequences."
:group 'x509-faces)
(defface x509-warning-face
'((t (:inherit font-lock-warning-face :inverse-video t)))
"Face for bad values."
:group 'x509-faces)
(defface x509-near-warning-face
'((t (:inherit font-lock-function-name-face :inverse-video nil)))
"Face for near expire date/time values."
:group 'x509-faces)
(defface x509-browse-url-face '((t (:inherit link)))
"Face for clickable URL links.")
(defface x509-asn1-hexl-header '((t (:inherit highlight :underline t)))
"Face for highlighting ASN.1 header in hexl buffer in `x509-asn1-mode'."
:group 'x509-faces)
(defface x509-asn1-hexl-value '((t (:inherit region)))
"Face for highlighting ASN.1 value in hexl buffer in `x509-asn1-mode'."
:group 'x509-faces)
(defun x509--normalize-buffer-end (buffer)
"Trim empty lines and ensure BUFFER ends in a newline."
(with-current-buffer buffer
(let ((delete-trailing-lines t))
(delete-trailing-whitespace (point-min) (point-max)))))
(defun x509--match-date (cmp bound)
"Return non-nil if it can find a date that CMP to current time.
Intended to search for dates in form \"Jun 11 00:00:01 2014 GMT\"
and compare them to the current time. Return non-nil, move point,
and set ‘match-data’ appropriately if it succeeds; like
‘re-search-forward’ would. The argument BOUND is a buffer
position that bounds the search."
(let ((mdata (match-data))
(p (point)))
(if (re-search-forward "[A-Z][a-z][a-z] +[0-9]+ ..:..:.. [0-9]\\{4\\} GMT"
bound
t)
(if (condition-case nil
;; Compare date to current time.
;; date-to-time might fail on bogus time values or if time
;; is to far in the past/future
(funcall cmp
(date-to-time (match-string-no-properties 0))
(current-time))
(error nil))
;; If compare true, return t.
t
;; else restore match-data and point and return nil.
(goto-char p)
(set-match-data mdata)
nil)
;; Not matching date at all -> return nil
nil)))
(defun x509--match-date-in-past (bound)
"Return non-nil if it can find a date that is the past.
Intended to search for dates in form \"Jun 11 00:00:01 2014 GMT\"
and compare them to the current time. Return non-nil, move point,
and set ‘match-data’ appropriately if it succeeds; like
‘re-search-forward’ would. The optional argument BOUND is a
buffer position that bounds the search."
(x509--match-date (lambda (d1 d2) (time-less-p d1 d2)) bound))
(defun x509--match-date-in-future (bound)
"Return non-nil if it can find a date that is the future.
Intended to search for dates in form \"Jun 11 00:00:01 2014 GMT\"
and compare them to the current time. Return non-nil, move point,
and set ‘match-data’ appropriately if it succeeds; like
‘re-search-forward’ would. The optional argument BOUND is a
buffer position that bounds the search."
(x509--match-date (lambda (d1 d2) (not (time-less-p d1 d2))) bound))
(defcustom x509-warn-near-expire-days 30
"Warn certificate expiration if time is near.
Set to nil to inhibit warning."
:type 'integer
:group 'x509)
(defcustom x509-query-oid-url-format "https://oid-rep.orange-labs.fr/get/%s"
"A format string for constructing URL for querying OIDs.
Used with `(format x509-query-oid-url-format oid)'"
:type 'string
:group 'x509)
(defcustom x509-swoop-separator ""
"A string that separates items in a buffer created by `x509-swoop'."
:type 'string
:group 'x509)
(defun x509--match-date-near-now (bound)
"Return non-nil it can find a date that is \"near\" in the future.
\"Near\" is defined by `x509-warn-near-expire-days'.
Intended to search for dates in form \"Jun 11 00:00:01 2014 GMT\"
and compare them to the current time. Return non-nil, move point,
and set ‘match-data’ appropriately if it succeeds; like
‘re-search-forward’ would. The optional argument BOUND is a
buffer position that bounds the search."
(x509--match-date
(lambda (time now)
;; If we should highlight near expire times
;; and time is not in the future
;; and time is within decoded-time-delta from now
(and x509-warn-near-expire-days
(time-less-p now time)
(time-less-p
time (time-add now (* x509-warn-near-expire-days 24 60 60)))))
bound))
(defun x509--mark-browse-url-links (regex face compose-url-fn)
"Make URLs clickable by making them buttons.
REGEX is used to find and delimit button.
FACE is the face to apply to the button.
COMPOSE-URL-FN is a function that takes a string and returns an URL.
For simple cases, COMPOSE-URL-FN returns its argument unchanged."
(save-excursion
(save-match-data
(goto-char (point-min))
(while (search-forward-regexp regex nil t)
(let* ((start (match-beginning 0))
(end (match-end 0))
(url (funcall compose-url-fn (match-string-no-properties 0)))
(help-echo (format "Click to browse-url %s" url)))
;; The url is stored in the face property
(make-button start end
'face
face
'follow-link
t
'url
url
'help-echo
help-echo
'action
(lambda (button)
(browse-url (button-get button 'url)))))))))
(defun x509--mark-browse-http-links ()
"Make http URLs clickable by making them buttons."
(x509--mark-browse-url-links
"\\(file\\|https?\\)://[-_.:/A-Za-z0-9]+"
'x509-browse-url-face
(lambda (url) url)))
(defun x509--mark-browse-oid ()
"Make OIDs clickable by making them buttons."
(x509--mark-browse-url-links
"\\(?:[0-9]+\\.\\)\\{3,\\}[0-9]+" 'x509-oid-link-face
(lambda (oid)
;; Require OID at least 4 nodes deep to avoid
;; false positives.
(format x509-query-oid-url-format oid))))
(eval-when-compile
(defun x509--load-data-file (filename)
"Split FILENAME linewise into a list.
Skip blank lines and comment lines. Return list."
;; Try to guess path to filename. It may not be in the current directory
;; when compiling.
(let ((path
(cond
((bound-and-true-p byte-compile-current-file)
(expand-file-name filename
(file-name-directory
byte-compile-current-file)))
((bound-and-true-p load-file-name)
(expand-file-name filename (file-name-directory load-file-name)))
(t
filename))))
(with-temp-buffer
(insert-file-contents path)
(cl-remove-if
(lambda (s) (string-match-p "^ *\\(?:#\\|$\\)" s))
(split-string (buffer-string) "\n"))))))
(eval-when-compile
(defconst x509--keywords (regexp-opt (x509--load-data-file "keywords.txt"))))
(eval-when-compile
(defconst x509--constants
(regexp-opt (x509--load-data-file "constants.txt") 'words)))
;; Keyword: constant
;; E.g. "Signature Algorithm: sha1WithRSAEncryption"
(eval-when-compile
(defconst x509--keyword-w-constant
(concat
(regexp-opt (x509--load-data-file "keyword+constant.txt") t)
;; Followed by ": constant"
": *\\(.*\\)")))
;; Multiline Issuer and Subject, "-nameopt multiline"
;; E.g. "commonName = GlobalSign Root CA"
(eval-when-compile
(defconst x509--multiline-name
(concat
(regexp-opt (x509--load-data-file "long-name.txt") t) " *= \\(.*\\)")))
(defconst x509-font-lock-keywords
(eval-when-compile
(list
;; Subject and Issuer, long names
`(,x509--multiline-name (1 'x509-keyword-face) (2 'x509-string-face))
`(,x509--keywords . 'x509-keyword-face)
`(,x509--constants . 'x509-constant-face)
;; Validity on a line alone (preceding "Not Before:")
'("^ +Validity ?$" . 'x509-keyword-face)
;; Subject and Issuer, short names
;; something=string until ',' or '/' or EOL
;; E.g. CN=apa,OU=Räv
'("\\(\\<\\w+=\\)\\(.*?\\)\\(?:[,/]\\|$\\)"
(1 'x509-short-name-face)
(2 'x509-string-face))
;; something = string until ',' or EOL
;; E.g. CN = ACCVRAIZ1, OU = PKIACCV, O = ACCV, C = ES
'("\\(\\<\\w+\\) = \\(.*?\\)\\(?:[,/]\\|$\\)"
(1 'x509-short-name-face)
(2 'x509-string-face))
;; URI: and CPS: . Highlight keyword. URL is handled by
;; `x509--mark-browse-url-links'
'("\\<\\(URI:\\|CPS: \\)" (1 'x509-keyword-face))
;; DNS:string email:string othername:string
;; until ',' or EOL
'("\\<\\(DNS:\\|email:\\|othername:\\)\\(.*?\\)\\(?:,\\|$\\)"
(1 'x509-keyword-face)
(2 'x509-string-face))
;; Not Before: Jun 11 00:00:01 2014 GMT
;; Date is "MATCH-ANCHORED", see help for variable font-lock-keywords
'("\\(Not Before\\): "
(1 'x509-keyword-face)
(x509--match-date-in-future nil nil (0 'x509-warning-face)))
'("\\(Not After\\) : "
(1 'x509-keyword-face)
(x509--match-date-in-past nil nil (0 'x509-warning-face))
(x509--match-date-near-now nil nil (0 'x509-near-warning-face)))
;; For CRL's when Next Update is in the past
'("\\(Next Update\\): "
(1 'x509-keyword-face)
(x509--match-date-in-past nil nil (0 'x509-warning-face)))
;; Policy: OID
;; Has precedence over Keyword: constant below
'("\\(Policy\\): \\([0-9]+\\.[0-9]+\\(:?\\.[0-9]+\\)*\\)"
(1 'x509-keyword-face)
(2 'x509-oid-face))
;; E.g. Public Key Algorithm: rsaEncryption
`(,x509--keyword-w-constant
(1 'x509-keyword-face) (2 'x509-constant-face))
;; CA:TRUE, CA:FALSE
;; CA used to be keyword+argument but CA: can be part of hex-string
'("\\(CA\\):\\(TRUE\\|FALSE\\)"
(1 'x509-keyword-face)
(2 'x509-constant-face))
;; Hex dumps At least two two-digit hex-numbers separated by `:'
;; Can end in `:' for example in "Modulus"
;; fa:09(:....)
'("[0-9a-fA-F][0-9a-fA-F]\\(?::[0-9a-fA-F][0-9a-fA-F]\\)+:?$"
.
'x509-hex-string-face)))
"OpenSSL x509 highlighting.")
(defun x509-mode-kill-buffer ()
"Kill current buffer."
(interactive)
(set-buffer-modified-p nil)
(kill-buffer))
;;;###autoload
(define-derived-mode
x509-mode
fundamental-mode
"x509"
"Major mode for displaying OpenSSL output.
\\{x509-mode-map}"
:interactive nil
:group
'x509
(set (make-local-variable 'font-lock-defaults) '(x509-font-lock-keywords t))
(keymap-set x509-mode-map "q" #'x509-mode-kill-buffer)
(keymap-set x509-mode-map "t" #'x509-toggle-mode)
(keymap-set x509-mode-map "e" #'x509-edit-params)
(keymap-set x509-mode-map "n" #'x509-dwim-next)
(keymap-set x509-mode-map "p" #'x509-dwim-prev)
(x509--mark-browse-http-links)
(x509--mark-browse-oid))
(defun x509--buffer-encoding (buffer)
"Heuristic for identifying PEM or DER encoding in BUFFER.
Return string \"PEM\" or \"DER\"."
(with-current-buffer buffer
(goto-char (point-min))
(save-match-data
(if (search-forward "-----BEGIN" nil t)
"PEM"
"DER"))))
(defconst x509--known-pki-types
'("CERTIFICATE"
"TRUSTED CERTIFICATE"
"CERTIFICATE REQUEST"
"DH PARAMETERS"
"EC PARAMETERS"
"PKCS7"
"ENCRYPTED PRIVATE KEY"
"PRIVATE KEY"
"RSA PRIVATE KEY"
"PUBLIC KEY"
"RSA PUBLIC KEY"
"X509 CRL")
"All the PEM region types known by `x509-mode'.
Other types will not be recognized as valid regions.")
(defun x509--known-region-type-p (type)
"Return non-nil if TYPE in a supported PKI type."
(member type x509--known-pki-types))
(defun x509--pem-region ()
"Determine if point is in region delimited by \"-----BEGIN\" \"-----END\".
Only consider regions whose type in known by `x509--known-region-type-p'.
Return (begin . end) or nil"
(save-excursion
(save-match-data
(let ((here (point)))
(if (or (looking-at "-----BEGIN \\(.*?\\)-----")
(re-search-backward "-----BEGIN \\(.*?\\)-----" nil t))
(let ((begin (match-beginning 0))
(type (match-string-no-properties 1)))
(if (and (search-forward (concat "-----END " type "-----") nil t)
(x509--known-region-type-p type)
;; Ensure point is between begin and end.
(< here (match-end 0)))
(cons begin (match-end 0)))))))))
(defun x509--pem-region-type ()
"Return type of pem region or nil if not matched.
Ex \"CERTIFICATE\" or \"DH PARAMETERS\""
(let ((region (x509--pem-region)))
(if region
(save-excursion
(save-match-data
(goto-char (car region))
(if (re-search-forward "-----BEGIN \\(.*?\\)-----" (cdr region) t)
(match-string-no-properties 1)))))))
(defun x509--generate-input-buffer ()
"Return a buffer containing data to be processed by OpenSSL.
Determine what portion of the current buffer is interesting to pass to
OpenSSL.
If point is in region delimited by \"-----BEGIN\" \"-----END\"
then that region is selected. The region is trimmed so that
leading and trailing non base-64 characters on each line are
removed. The idea is to be able to view, for example, a
certificate that is embedded as string in code.
If point is not in a PEM region, the whole buffer is used."
(let* ((region (x509--pem-region))
(begin
(if region
(car region)
(point-min)))
(end
(if region
(cdr region)
(point-max)))
(data
(if region
(buffer-substring-no-properties begin end)))
(src-buffer (current-buffer))
(new-buf
(generate-new-buffer
(generate-new-buffer-name (format " *in-x-%s*" (buffer-name))))))
(with-current-buffer new-buf
(set-buffer-file-coding-system 'no-conversion)
(if data
(insert data)
(insert-buffer-substring-no-properties src-buffer))
;; If in PEM region, try to strip non base-64 characters
(when region
(goto-char (point-min))
(while (re-search-forward "^[^-A-Za-z0-9+=/]+\\|[^-A-Za-z0-9+=/]+$"
nil
t)
(replace-match "" nil nil))
;; Strip \n from eol. Can be seen in C code.
(goto-char (point-min))
(while (re-search-forward "\\\\n$" nil t)
(replace-match "" nil nil)))
new-buf)))
(defmacro x509-defvar-local-persistent (var-name docstring)
"Define a buffer-local variable VAR-NAME with DOCSTRING.
Make it persist during major mode change."
`(progn
(defvar-local ,var-name nil
,docstring)
(put ',var-name 'permanent-local t)))
(x509-defvar-local-persistent
x509--src-buffer "Original buffer where x509 view command was run.")
(x509-defvar-local-persistent
x509--shadow-buffer "Input buffer used for OpenSSL command.")
(x509-defvar-local-persistent
x509--x509-mode-shadow-arguments
"Current OpenSSL command arguments used in `x509-mode'.")
(x509-defvar-local-persistent
x509--x509-asn1-mode-shadow-arguments
"Current OpenSSL command argument used in `x509-asn1-mode'.")
(x509-defvar-local-persistent
x509--x509-asn1-mode-offset-stack
"Stack of (command start header-len pos) for strparse/offset.
In `x509-asn1-mod'.
POS is the buffer position when going down. Used to restore pos
when going back up.")
(x509-defvar-local-persistent
x509-asn1--last-point
"Used to detect when the point has moved.
For updating overlay in hexl buffer.")
(x509-defvar-local-persistent
x509-asn1--hexl-buffer
"Hexl buffer that follows current line in `x509-asn1-mode'.")
(x509-defvar-local-persistent
x509-asn1--hexl-overlays "Current overlays in hexl buffer.")
(defun x509--kill-shadow-buffer ()
"Kill buffer hook function.
Run when killing a view buffer for cleaning up associated input buffer.
Also kill any hexl buffer."
(when (and (boundp 'x509--shadow-buffer) (buffer-live-p x509--shadow-buffer))
(kill-buffer x509--shadow-buffer))
(when (and (boundp 'x509-asn1--hexl-buffer)
(buffer-live-p x509-asn1--hexl-buffer))
(kill-buffer x509-asn1--hexl-buffer)))
(defun x509--process-buffer
(input-buf openssl-arguments &optional output-buf no-hooks)
"Create new buffer named \"*x-[buffer-name]*\".
Pass content INPUT-BUF to openssl with
OPENSSL-ARGUMENTS. E.g. x509 -text. If OUTPUT-BUF is non-'nil',
out to that buffer instead of generating a new one.
When NO-HOOKS is not nil, `kill-buffer-hook' and
`x509--shadow-buffer' are not set. Can be used when decoding
base64 and result buffer does not need special hooks or
variables. NO-HOOKS also ensures that process output isn't
decoded, i.e. data is inserted into buffer as binary.
Return output buffer."
(let* ((buf
(or output-buf
(generate-new-buffer
(generate-new-buffer-name (format "*x-%s*" (buffer-name))))))
;; Operate on whole buffer. Output to buf
(args
(append
(list nil nil x509-openssl-cmd nil buf nil) openssl-arguments)))
(with-current-buffer buf
(setq buffer-read-only nil)
(erase-buffer)
(unless no-hooks
;; Remember input-buffer and arguments.
(setq x509--shadow-buffer input-buf)
(add-hook 'kill-buffer-hook #'x509--kill-shadow-buffer nil t))
(with-current-buffer input-buf
(if no-hooks
(let ((coding-system-for-read 'no-conversion)
(coding-system-for-write 'no-conversion))
(apply #'call-process-region args))
(apply #'call-process-region args)))
;; Since OpenSSL 3, there is a warning when reading input from stdin and
;; not from a file specified by an -in parameter. Delete that warning
;; line from the output. "Warning: Reading certificate from stdin since
;; no -in or -new option is given". Also seen:
;; "Warning: Will read cert request from stdin since no -in option is
;; given"
(goto-char (point-min))
(if (looking-at-p "Warning: .*stdin")
(delete-line))
(set-buffer-modified-p nil)
(setq buffer-read-only t))
buf))
(defun x509--read-arguments (prompt default history)
"Prompt, using PROMPT, for arguments if \\[universal-argument] prefix.
Provide DEFAULT argument and HISTORY.
Return argument string."
(let ((history-delete-duplicates t))
(if (equal current-prefix-arg '(4))
(read-from-minibuffer prompt default nil nil history)
(progn
(add-to-history history default)
default))))
(defun x509--add-inform-spec (arguments encoding)
"Add or modify \"-inform ENCODING\" in ARGUMENTS."
(if (string-match "-inform \\(PEM\\|DER\\)" arguments)
(replace-match encoding nil nil arguments 1)
(format "%s -inform %s" arguments encoding)))
(defun x509--generic-view (default history mode &optional input-buf output-buf)
"Prepare an input buffer for data to be processed.
Optionally get modified command arguments from user.
Process data from input buffer using command arguments.
DEFAULT is the initial command line arguments to OpenSSL.
HISTORY is the command history symbol used with
`read-from-minibuffer'. MODE is the major mode that will be
applied to the result buffer. If INPUT-BUF is non-'nil', use
existing input buffer instead of creating one. If OUTPUT-BUF is
non-'nil', use that instead of creating a new one.
Switch to resulting buffer and return it."
(let* ((src-buffer (current-buffer))
(in-buf (or input-buf (x509--generate-input-buffer)))
(encoding (x509--buffer-encoding in-buf))
(initial (x509--add-inform-spec default encoding))
(args (x509--read-arguments "arguments: " initial history))
(result-buffer
(x509--process-buffer in-buf (split-string-and-unquote args)
output-buf)))
(switch-to-buffer result-buffer)
(unless (bound-and-true-p x509--src-buffer)
;; Remember the original source buffer unless already set.
;; Which is can be if toggling between modes.
(setq x509--src-buffer src-buffer))
;; Remember what arguments where used.
(if (eq mode 'x509-mode)
(setq x509--x509-mode-shadow-arguments args)
(setq x509--x509-asn1-mode-shadow-arguments args))
(funcall mode)
;; If we have a hexl buffer, (re-)add hook that updates overlays.
;; The post-command-hook seems to be reset when changing mode.
;; Is there a way to make it persist mode changes?
;; Also re-set last point so that overlay is updated.
(when (bound-and-true-p x509-asn1--hexl-buffer)
(add-hook 'post-command-hook #'x509-asn1--post-command-hook nil t)
(setq x509-asn1--last-point nil))
result-buffer))
(defun x509--get-x509-toggle-mode-args ()
"Ask user for command and return default arguments for that command."
(let* ((collection
'(("cert" . x509-x509-default-arg)
("req" . x509-req-default-arg)
("crl" . x509-crl-default-arg)
("pkcs7" . x509-pkcs7-default-arg)
("dhparam" . x509-dhparam-default-arg)
("key" . x509-pkey-default-arg)
("publickey" . x509-pkey-pubin-default-arg)
("asn1parse" . x509-asn1parse-default-arg)))
(choice
(completing-read
"Parse as: " ; PROMPT
collection ; COLLECTION
nil ; PREDICATE
t ; REQUIRE-MATCH
)))
(symbol-value (cdr (assoc choice collection)))))
(defun x509--get-x509-history (args)
"Return history variable that matches command ARGS."
(pcase (car (split-string-and-unquote args))
("x509" 'x509--viewcert-history)
("req" 'x509--viewreq-history)
("crl" 'x509--viewcrl-history)
("pkcs7" 'x509--viewpkcs7-history)
("dhparam" 'x509--viewdh-history)
("ecparam" 'x509--viewec-history)
("pkey" (if (string-match-p "-pubin" args)
'x509--viewpublickey-history
'x509--viewkey-history))
("asn1parse" 'x509--viewasn1-history)
(_ nil)))
(defun x509-toggle-mode (&optional edit)
"Toggle between asn1-mode and `x509-mode'.
If EDIT is non-'nil', edit current command arguments and redisplay."
(interactive)
(if edit
(setq current-prefix-arg '(4)))
(if (or (and edit (derived-mode-p 'x509-asn1-mode)) ; Edit asn1 mode
(and (not edit) (derived-mode-p 'x509-mode))) ; Toggle to asn1
(let ((default-args
(or x509--x509-asn1-mode-shadow-arguments
x509-asn1parse-default-arg)))
(x509--generic-view
default-args 'x509--viewasn1-history 'x509-asn1-mode
x509--shadow-buffer (current-buffer)))
(let* ((default-args
(or x509--x509-mode-shadow-arguments
(x509--get-x509-toggle-mode-args)))
(history (x509--get-x509-history default-args)))
(x509--generic-view default-args history 'x509-mode
x509--shadow-buffer
(current-buffer)))))
(defun x509-edit-params ()
"Edit command parameters in current buffer."
(interactive)
(x509-toggle-mode t))
;; ---------------------------------------------------------------------------
(defvar x509--viewcert-history nil
"History list for `x509-viewcert'.")
;;;###autoload
(defun x509-viewcert ()
"Parse current buffer as a certificate file.
With \\[universal-argument] prefix, you can edit the command arguments."
(interactive)
(x509--generic-view
x509-x509-default-arg 'x509--viewcert-history 'x509-mode))
;; ---------------------------------------------------------------------------
(defvar x509--viewreq-history nil
"History list for `x509-viewreq'.")
;;;###autoload
(defun x509-viewreq ()
"Parse current buffer as a certificate request file.
With \\[universal-argument] prefix, you can edit the command arguments."
(interactive)
(x509--generic-view x509-req-default-arg 'x509--viewreq-history 'x509-mode))
;; ---------------------------------------------------------------------------
(defvar x509--viewcrl-history nil
"History list for `x509-viewcrl'.")
;;;###autoload
(defun x509-viewcrl ()
"Parse current buffer as a CRL file.
With \\[universal-argument] prefix, you can edit the command arguments."
(interactive)
(x509--generic-view x509-crl-default-arg 'x509--viewcrl-history 'x509-mode))
;; ---------------------------------------------------------------------------
(defvar x509--viewpkcs7-history nil
"History list for `x509-viewpkcs7'.")
;;;###autoload
(defun x509-viewpkcs7 ()
"Parse current buffer as a PKCS#7 file.
Output only certificates and CRLs by default. Add the \"-print\"
switch to output details.
With \\[universal-argument] prefix, you can edit the command arguments."
(interactive)
(x509--generic-view
x509-pkcs7-default-arg 'x509--viewpkcs7-history 'x509-mode))
;; ---------------------------------------------------------------------------
(defvar x509--viewdh-history nil
"History list for `x509-viewdh'.")
;;;###autoload
(defun x509-viewdh ()
"Parse current buffer as a DH-parameter file.
With \\[universal-argument] prefix, you can edit the command arguments."
(interactive)
(x509--generic-view
x509-dhparam-default-arg 'x509--viewdh-history 'x509-mode))
;; ---------------------------------------------------------------------------
(defvar x509--viewec-history nil
"History list for `x509-viewec'.")
;;;###autoload
(defun x509-viewec ()
"Parse current buffer as a EC-parameter file.
With \\[universal-argument] prefix, you can edit the command arguments."
(interactive)
(x509--generic-view
x509-ecparam-default-arg 'x509--viewec-history 'x509-mode))
;; ---------------------------------------------------------------------------
(defvar x509--viewkey-history nil
"History list for `x509-viewkey'.")
;;;###autoload
(defun x509-viewkey ()
"Display x509 private key using the OpenSSL pkey command.
With \\[universal-argument] prefix, you can edit the command arguments."
(interactive)
(x509--generic-view x509-pkey-default-arg 'x509--viewkey-history 'x509-mode))
;; ---------------------------------------------------------------------------
(defvar x509--viewpublickey-history nil
"History list for `x509-publicviewkey'.")
;;;###autoload
(defun x509-viewpublickey ()
"Display x509 public key using the OpenSSL pkey command.
With \\[universal-argument] prefix, you can edit the command arguments."
(interactive)
(x509--generic-view
x509-pkey-pubin-default-arg 'x509--viewpublickey-history 'x509-mode))
;; ---------------------------------------------------------------------------
(defvar x509--viewlegacykey-history nil
"History list for `x509-viewlegacykey'.")
;; Special. older openssl pkey cannot read from stdin so we need to use
;; buffer's file.
;;;###autoload
(defun x509-viewlegacykey (&optional args)
"Display x509 private key using the OpenSSL pkey command.
This function works with older OpenSSL that could not read key from
stdin. Instead, the buffer file is used with -in.
ARGS are arguments to the openssl command.
With \\[universal-argument] prefix, you can edit the command arguments.
For example to enter pass-phrase, add -passin pass:PASSPHRASE."
(interactive (list
(x509--read-arguments
"pkey args: "
(format "%s -inform %s -in \"%s\""
x509-pkey-default-arg
(x509--buffer-encoding (current-buffer))
(buffer-file-name))
'x509--viewlegacykey-history)))
(let* ((buf
(generate-new-buffer
(generate-new-buffer-name (format "*x-%s*" (buffer-name))))))
(setq args
(append
(list x509-openssl-cmd nil buf nil)
(split-string-and-unquote args)))
(apply #'call-process args)
(switch-to-buffer buf)
(goto-char (point-min))
(set-buffer-modified-p nil)
(setq buffer-read-only t)
(x509-mode)))
(defun x509--pem-region-next/prev (buffer direction)
"Find BEGIN before or after current region and place point at beginning.
BUFFER is the buffer to search in.
DIRECTION is one of \\='next \\='prev
Return (begin . end) if region is found.
Return nil if not in a region or next/prev region isn't found.
If no next/prev region, leave point unchanged."
(let* ((is-next (eq direction 'next))
(search-fn
(if is-next
're-search-forward
're-search-backward))
;; Get either cdr for end of current region when searching forward
;; or car for beginning of current region when searching backwards
(region-point-fn
(if is-next
'cdr
'car)))
(with-current-buffer buffer
(if-let* ((current-region (x509--pem-region))
(current-begin (funcall region-point-fn current-region))
(current-point (point)))
(let (new-region)
(goto-char current-begin)
;; Look for next/prev region
(while (and (not new-region) (funcall search-fn "-----BEGIN" nil t))
(goto-char (match-beginning 0))
(setq new-region (x509--pem-region))
;; If this BEGIN was bogus. Move a bit and look for another
(if (not new-region)
;; Only need to move if searching forward so as not to hit the
;; same match again.
(if is-next
(forward-char 1))))
(if (not new-region)
;; Restore point since we didn't find any new region
(goto-char current-point))
;; Return new region. Maybe nil
new-region)))))
(defun x509--dwim-next/prev (direction)
"Look for a PEM region before of after the current one.
DIRECTION is either \\='next or \\='prev
If found, kill current buffer, switch to src buffer and call `x509-dwim'.
Intended to be called in a `x509-mode' or `x509-asn1-mode' buffer."
(if (not (bound-and-true-p x509--src-buffer))
(message "Not in an x509 buffer")
;; Find prev region in original buffer
(let* ((new-region (x509--pem-region-next/prev x509--src-buffer direction))
(name
(if (eq direction 'next)
"next"
"previous")))
(if (not new-region)
(progn
(message "No %s" name)
nil)