First pass at supporting date/time added for Trust Anchors
[moonshot-ui.git] / src / moonshot-id.vala
1 /*
2  * Copyright (c) 2011-2016, JANET(UK)
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * 3. Neither the name of JANET(UK) nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31 */
32
33 using Gee;
34
35 extern char* get_cert_valid_before(uchar* inbuf, int inlen, char* outbuf, int outlen);
36
37
38 // A TrustAnchor object can be imported or installed via the API, but cannot
39 // be modified by the user, other than being cleared. Hence the fields are read-only.
40 public class TrustAnchor : Object
41 {
42     private static const string CERT_HEADER = "-----BEGIN CERTIFICATE-----";
43     private static const string CERT_FOOTER = "-----END CERTIFICATE-----";
44
45     public enum TrustAnchorType {
46         CA_CERT,
47         SERVER_CERT
48     }
49  
50     private string _ca_cert = "";
51     private string _subject = "";
52     private string _subject_alt = "";
53     private string _server_cert = "";
54     private string _datetime_added = "";
55     public bool user_verified = false;
56
57     private static string fixup (string s) {
58         return (s == null ? "" : s.strip());
59     }
60
61     public TrustAnchor(string ca_cert, string server_cert, string subject, string subject_alt, bool user_verified) {
62         _ca_cert = fixup(ca_cert);
63         _server_cert = fixup(server_cert);
64         _subject = fixup(subject);
65         _subject_alt = fixup(subject_alt);
66         this.user_verified = user_verified;
67
68         // If we're reading from store, this will be overridden (see set_datetime_added)
69         _datetime_added = "";
70     }
71
72     public TrustAnchor.empty() {
73     }
74
75
76     public string ca_cert {
77         get {
78             return _ca_cert;
79         }
80     }
81
82     public string subject {
83         get {
84             return _subject;
85         }
86     }
87
88     public string subject_alt  {
89         get {
90             return _subject_alt;
91         }
92     }
93
94
95     public string server_cert {
96         get {
97             return _server_cert;
98         }
99     }
100
101     public string datetime_added {
102         get {
103             return _datetime_added;
104         }
105     }
106
107     public bool is_empty() {
108         return ca_cert == "" && subject == "" && subject_alt == "" && server_cert == "";
109     }
110
111     public TrustAnchorType get_anchor_type() {
112         return server_cert == "" ? TrustAnchorType.CA_CERT : TrustAnchorType.SERVER_CERT;
113     }
114
115     internal void set_datetime_added(string datetime) {
116         _datetime_added = fixup(datetime);
117     }
118
119     internal static string format_datetime_now() {
120         DateTime now = new DateTime.now_utc();
121         string dt = now.format("%b %d %T %Y %Z");
122         return dt;
123     }
124
125     public int Compare(TrustAnchor other)
126     {
127         if (this.ca_cert != other.ca_cert) {
128             return 1;
129         }
130         if (this.subject != other.subject) {
131             return 1;
132         }
133         if (this.subject_alt != other.subject_alt) {
134             return 1;
135         }
136         if (this.server_cert != other.server_cert) {
137             return 1;
138         }
139         if (this.user_verified != other.user_verified) {
140             return 1;
141         }
142         // if (!is_empty() && this.datetime_added != other.datetime_added) {
143         //     return 1;
144         // }
145         return 0;
146     }
147
148     public string? get_expiration_date(out string? err_out=null)
149     {
150         if (this.ca_cert == "") {
151             if (&err_out != null) {
152                 err_out = "Trust anchor does not have a ca_certificate";
153                 return null;
154             }
155         }
156
157         string cert = this.ca_cert;
158         cert.chomp();
159
160         uchar[] binary = Base64.decode(cert);
161         IdCard.logger.trace("get_expiration_date: encoded length=%d; decoded length=%d".printf(cert.length, binary.length));
162
163         char buf[64];
164         string err = (string) get_cert_valid_before(binary, binary.length, buf, 64);
165         if (err != "") {
166             IdCard.logger.error(@"get_expiration_date: get_cert_valid_before returned '$err'");
167             if (&err_out != null) {
168                 err_out = err;
169             }
170             return null;
171         }
172             
173         string date = (string) buf;
174         IdCard.logger.trace(@"get_expiration_date: get_cert_valid_before returned '$date'");
175
176         return date;
177     }
178 }
179
180
181 public struct Rule
182 {
183     public string pattern;
184     public string always_confirm;
185     public int Compare(Rule other) {
186         if (this.pattern != other.pattern)
187             return 1;
188         if (this.always_confirm != other.always_confirm)
189             return 1;
190         return 0;
191     }
192 }
193
194 public class IdCard : Object
195 {
196     internal static MoonshotLogger logger = get_logger("IdCard");
197
198     public const string NO_IDENTITY = "No Identity";
199
200     private string _nai;
201   
202     public string display_name { get; set; default = ""; }
203   
204     public string username { get; set; default = ""; }
205 #if GNOME_KEYRING
206     private unowned string _password;
207     public string password {
208         get {
209             return (_password!=null) ? _password : "";
210         }
211         set {
212             if (_password != null) {
213                 GnomeKeyring.memory_free((void *)_password);
214                 _password = null;
215             }
216             if (value != null)
217                 _password = GnomeKeyring.memory_strdup(value); 
218         }
219     }
220 #else
221     public string password { get; set; default = null; }
222 #endif
223
224     public string issuer { get; set; default = ""; }
225   
226     private Rule[] _rules = new Rule[0];
227     public Rule[] rules {
228         get {return _rules;}
229         internal set {_rules = value ?? new Rule[0] ;}
230     }
231
232     private ArrayList<string> _services = new ArrayList<string>();
233
234     internal ArrayList<string> services {
235          get {return  _services;}
236     }
237
238     // Returns the list of services as a string, using the given separator.
239     internal string get_services_string(string sep) {
240         if (_services.is_empty) {
241             return "";
242         }
243
244         // ArrayList.to_array() seems to be unreliable -- it causes segfaults 
245         // semi-randomly. (Possibly because it returns an unowned ref?)
246         // return string.joinv(sep, _services.to_array());
247         // 
248         // This problem may be related to the one noted elsewhere as the
249         // "Centos vala array property bug".
250
251         string[] svcs = new string[_services.size];
252         for (int i = 0; i < _services.size; i++) {
253             svcs[i] = _services[i];
254         }
255
256         return string.joinv(sep, svcs);
257     }
258
259     internal void update_services(string[] services) {
260         _services.clear();
261
262         // Doesn't exist in older versions of libgee:
263         // _services.add_all_array(services);
264
265         if (services != null) {
266             foreach (string s in services) {
267                 _services.add(s);
268             }
269         }
270     } 
271
272     internal void update_services_from_list(ArrayList<string> services) {
273         if (services == this._services) {
274             // Don't try to update from self.
275             return;
276         }
277
278         _services.clear();
279
280         if (services != null) {
281             _services.add_all(services);
282         }
283     } 
284
285
286     public bool temporary {get; set; default = false; }
287
288     private TrustAnchor _trust_anchor = new TrustAnchor.empty();
289     public TrustAnchor trust_anchor  { 
290         get {
291             return _trust_anchor;
292         }
293     }
294
295     // For use by storage implementations.
296     internal void set_trust_anchor_from_store(TrustAnchor ta) {
297         _trust_anchor = ta;
298     }
299
300     internal void clear_trust_anchor() {
301         _trust_anchor = new TrustAnchor.empty();
302     }
303   
304     public unowned string nai { get {  _nai = username + "@" + issuer; return _nai;}}
305
306     public bool store_password { get; set; default = false; }
307
308     public bool is_no_identity() 
309     {
310         return (display_name == NO_IDENTITY);
311     }
312
313     public enum DiffFlags {
314         DISPLAY_NAME,
315         USERNAME,
316         PASSWORD,
317         ISSUER,
318         RULES,
319         SERVICES,
320         TRUST_ANCHOR;
321     }
322
323     public int Compare(IdCard other)
324     {
325         int diff = 0;
326         if (this.display_name != other.display_name)
327             diff |= 1 << DiffFlags.DISPLAY_NAME;
328
329         if (this.username != other.username)
330             diff |= 1 << DiffFlags.USERNAME;
331
332         if (this.password != other.password)
333             diff |= 1 << DiffFlags.PASSWORD;
334
335         if (this.issuer != other.issuer)
336             diff |= 1 << DiffFlags.ISSUER;
337
338         if (CompareRules(this.rules, other.rules)!=0)
339             diff |= 1 << DiffFlags.RULES;
340
341         if (CompareStringArrayList(this._services, other._services)!=0)
342             diff |= 1 << DiffFlags.SERVICES;
343
344         if (this.trust_anchor.Compare(other.trust_anchor)!=0)
345             diff |= 1 << DiffFlags.TRUST_ANCHOR;
346
347         // stdout.printf("Diff Flags: %x\n", diff);
348         if (this.display_name == other.display_name && diff != 0) {
349             logger.trace("Compare: Two IDs with display_name '%s', but diff_flags=%0x".printf(this.display_name, diff));
350         }
351         return diff;
352     }
353
354     public static IdCard NewNoIdentity() 
355     { 
356         IdCard card = new IdCard();
357         card.display_name = NO_IDENTITY;
358         return card;
359     }
360
361     ~IdCard() {
362         password = null;
363     }
364
365     internal void add_rule(Rule rule) {
366         _rules += rule;
367     }
368 }
369
370 public int CompareRules(Rule[] a, Rule[] b)
371 {
372     if (a.length != b.length) {
373         return 1;
374     }
375
376     for (int i = 0; i < a.length; i++) {
377         if (a[i].Compare(b[i]) != 0) {
378             return 1;
379         }
380     }
381     return 0;
382 }
383
384 public int CompareStringArrayList(ArrayList<string> a, ArrayList<string> b)
385 {
386     if (a.size != b.size) {
387         return 1;
388     }
389
390     for (int i = 0; i < a.size; i++) {
391         if (a[i] != b[i]) {
392             return 1;
393         }
394     }
395     return 0;
396 }