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
  
#pike __REAL_VERSION__ 
#pragma strict_types 
 
//! Support for parsing PEM-style messages, defined in @rfc{1421@}. 
//! Encapsulation defined in @rfc{934@}. 
 
//! Key derivation function used in PEM. 
//! 
//! @fixme 
//!   Derived from OpenSSL. Is there any proper specification? 
//! 
//!   It seems to be related to PBKDF1 from @rfc{2898@}. 
string(8bit) derive_key(string(8bit) password, string(8bit) salt, int bytes) 
{ 
  string(8bit) out = ""; 
  string(8bit) hash = ""; 
  string(8bit) junk = password + salt; 
  password = "CENSORED"; 
  while (sizeof(out) < bytes) { 
    hash = Crypto.MD5.hash(hash + junk); 
    out += hash; 
  } 
  return out[..bytes-1]; 
} 
 
//! Decrypt a PEM body. 
//! 
//! @param dek_info 
//!   @expr{"dek-info"@} header from the @[Message]. 
//! 
//! @param body 
//!   Encypted PEM body. 
//! 
//! @param password 
//!   Decryption password. 
//! 
//! @returns 
//!   Returns the decrypted body text. 
string decrypt_body(string(8bit) dek_info, string(8bit) body, string(8bit) password) 
{ 
  string(8bit) key = password; 
  password = "CENSORED"; 
  if (!dek_info) return body; 
  array(string) d = dek_info/","; 
  if (sizeof(d) != 2) error("Unsupported DEK-Info.\n"); 
  string method = lower_case(String.trim(d[0])); 
  Crypto.AES.CBC._Buffer cipher = ([ 
    "des-cbc": Crypto.DES.CBC.Buffer, 
    "des-ede3-cbc": Crypto.DES3.CBC.Buffer, 
    "aes-128-cbc": Crypto.AES.CBC.Buffer, 
    "aes-192-cbc": Crypto.AES.CBC.Buffer, 
    "aes-256-cbc": Crypto.AES.CBC.Buffer, 
  ])[method]; 
  if (!cipher) error("Unsupported cipher suite.\n"); 
  int key_size = ([ 
    "des-cbc": 8, 
    "aes-128-cbc": 16, 
    "aes-256-cbc": 32, 
  ])[method] || 24; 
  string(8bit) iv = String.hex2string(d[1]); 
  key = derive_key(key, iv[..7], key_size); 
  Crypto.AES.CBC.Buffer.State decoder = cipher(); 
  decoder->set_decrypt_key(key); 
  return decoder->unpad(iv + body, Crypto.PAD_PKCS7)[sizeof(iv)..]; 
} 
 
//! Decrypt a PEM Message. 
//! 
//! @param body 
//!   Fragment with encypted PEM body. 
//! 
//! @param password 
//!   Decryption password. 
//! 
//! @returns 
//!   Returns the decrypted body text. 
string decrypt_fragment(Message m, string(8bit) pwd) 
{ 
  // FIXME: Check proc-type = "4,ENCRYPTED"? 
  string(8bit) dek = m->headers["dek-info"]; 
  if(!dek) return 0;; 
  return decrypt_body(dek, m->body, pwd); 
} 
 
//! Represents a PEM-style message. 
class Message 
{ 
  //! Pre-encapsulation boundary string. 
  //! 
  //! Typically a string like @expr{"CERTIFICATE"@} or @expr{"PRIVATE KEY"@}. 
  string pre; 
 
  //! Post-encapsulation boundary string. 
  //! 
  //! Usually the same value as @[pre]. 
  string post; 
 
  //! Encapsulated headers. If headers occur multiple times, they 
  //! will be concatenated separated by delimiting NUL characters. 
  mapping(string(8bit):string(8bit)) headers; 
 
  //! The decode message body. 
  string(8bit) body; 
 
  //! Message trailer, like @rfc{4880@} checksum. 
  string trailer; 
 
  protected void create(string|array(string) data) 
  { 
    array(string) lines; 
    if(stringp(data)) 
    { 
       lines = data/"\n"; 
       while(sizeof(lines) && lines[-1]=="") 
         lines = lines[..<1]; 
    } 
    else 
      lines = [array(string)]data; 
 
    if( sscanf(lines[0], "%*[ \t]-----BEGIN %s-----", pre)!=2 ) 
      return; 
 
    lines = lines[1..]; 
    if( sscanf(lines[-1], "%*[ \t]-----END %s-----", post)==2 ) 
    { 
      lines = lines[..<1]; 
    } 
 
    if( sizeof(lines[-1]) && lines[-1][0]=='=' ) 
    { 
      trailer = MIME.decode_base64(lines[-1][1..]); 
      lines = lines[..<1]; 
    } 
 
    array res = MIME.parse_headers(lines*"\n"); 
    headers = [mapping(string(8bit):string(8bit))]res[0]; 
    body = MIME.decode_base64([string(8bit)]res[1]); 
  } 
} 
 
//! The Messages class acts as an envelope for a PEM message file or 
//! stream. 
class Messages 
{ 
  //! The fragments array contains the different message fragments, as 
  //! Message objects for decoded messages and strings for 
  //! non-messages or incomplete messages. 
  array(string|Message) fragments = ({}); 
 
  //! This is a mapping from encapsulation boundary string to Message 
  //! objects. All message objects and surrounding text will be 
  //! listed, in order, in @[fragments]. 
  mapping(string:array(Message)) parts = ([]); 
 
  //! A Messages object is created with the file or stream data. 
  protected void create(string data) 
  { 
    array(string) current = ({}); 
    foreach(data/"\n";; string line) 
    { 
      if( has_prefix(line, "-----BEGIN ") ) 
      { 
        // RFC1421 section 4.4p3 allows for multiple pre-EB 
        fragments += process(current); 
        current = ({ line }); 
      } 
      else if( has_prefix(line, "-----END ") ) 
      { 
        current += ({ line }); 
        fragments += process(current); 
        current = ({}); 
      } 
      else 
        current += ({ line }); 
    } 
    if(sizeof(current)) 
      fragments += process(current); 
 
    foreach(fragments;; string|Message part) 
      if(objectp(part)) 
      { 
        Message msg = [object(Message)]part; 
        parts[msg->pre] += ({ msg }); 
      } 
  } 
 
  protected array(string|Message) process(array(string) lines) 
  { 
    if( !sizeof(lines) || !has_prefix(lines[0], "-----BEGIN ") ) 
      return ({ lines*"\n" }); 
    return ({ Message(lines) }); 
  } 
 
  //! Returns an array of all fragments with any of the given 
  //! @[labels] in the boundy preamble. 
  array(Message) get_fragments(multiset labels) 
  { 
    array(Message) ret = ({}); 
    foreach(fragments, string|Message m) 
    { 
      if(objectp(m) && labels[m->pre]) 
        ret += ({ m }); 
    } 
    return ret; 
  } 
 
  //! Returns an array of the string bodies of all fragments with any 
  //! of the given @[labels] in the boundy preamble. 
  array(string) get_fragment_bodies(multiset labels) 
  { 
    return get_fragments(labels)->body; 
  } 
 
  //! Returns an array of all the bodies of @expr{"CERTIFICATE"@} and 
  //! @expr{"X509 CERTIFICATE"@} fragments. 
  array(string) get_certificates() 
  { 
    // FIXME: Support "TRUSTED CERTIFICATE" that contains additional 
    // information (trusted uses, rejected uses, alias and key id). 
    return get_fragment_bodies( (< "CERTIFICATE", "X509 CERTIFICATE" >) ); 
  } 
 
  //! Convenience wrapper for @[get_certificates] that returns the 
  //! first available certificate, or @expr{0@}. 
  string get_certificate() 
  { 
    return get_certificates()[?0]; 
  } 
 
  protected array(Message) low_get_private_keys() 
  { 
    return get_fragments( (< "RSA PRIVATE KEY", "DSA PRIVATE KEY", 
                             "EC PRIVATE KEY", "ANY PRIVATE KEY" >) ); 
  } 
 
  //! Returns an array of all the bodies of @expr{"RSA PRIVATE KEY"@}, 
  //! @expr{"DSA PRIVATE KEY"@}, @expr{"EC PRIVATE KEY"@} and 
  //! @expr{"ANY PRIVATE KEY"@} fragments. 
  array(string) get_private_keys() 
  { 
    return low_get_private_keys()->body; 
  } 
 
  //! Convenience wrapper for @[get_private_key] that returns the 
  //! first available key, or @expr{0@}. 
  string get_private_key() 
  { 
    return get_private_keys()[?0]; 
  } 
 
  //! Returns the first key, decoded by the @[pwd] password. 
  string get_encrypted_private_key(string(8bit) pwd) 
  { 
    Message m = low_get_private_keys()[?0]; 
    if(!m) return 0; 
    return decrypt_fragment(m, pwd); 
  } 
 
  protected string _sprintf(int t) 
  { 
    return t=='O' && sprintf("Standards.PEM.Message%O", parts); 
  } 
} 
 
//! Convenience function that decodes a PEM message containing only 
//! one part, and returns it as a string. Returns @expr{0@} for indata 
//! containing no or multiple parts. 
string simple_decode(string pem) 
{ 
  Messages m = Messages(pem); 
  return sizeof(m->parts)==1 && 
    sizeof(values(m->parts)[0])==1 && 
    values(m->parts)[0][0]->body; 
} 
 
//! Creates a PEM message, wrapped to 64 character lines. 
//! 
//! @param tag 
//!   The encapsulation boundary string. 
//! 
//! @param data 
//!   The data to be encapsulated. 
//! 
//! @param headers 
//!   Optional mapping containing encapsulated headers as name value 
//!   pairs. 
//! 
//! @param checksum 
//!   Optional checksum string, added as per @rfc{4880@}. 
string build(string tag, string data, 
             void|mapping(string:string) headers, 
             void|string checksum) 
{ 
  String.Buffer out = String.Buffer(); 
  out->add("-----BEGIN ", tag, "-----\n"); 
  if(headers) 
  { 
    if (headers["proc-type"]) { 
      // The Proc-Type header MUST come first. 
      // RFC 1421 4.6.1.1. 
      out->add("Proc-Type: ", headers["proc-type"], "\n"); 
    } 
    foreach(sort(indices([mapping(string:string)]headers)), string name) { 
      if (name == "proc-type") continue; 
      out->add(name, ": ", headers[name], "\n"); 
    } 
  } 
 
  foreach(MIME.encode_base64(data,1)/64.0, string line) 
    out->add("\n", line); 
 
  if( checksum ) 
    out->add("\n=", MIME.encode_base64(checksum, 1)); 
  out->add("\n-----END ", tag, "-----\n"); 
  return (string)out; 
}