Various stability fixes and logging improvements
[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         EMPTY,
47         CA_CERT,
48         SERVER_CERT
49     }
50  
51     private string _ca_cert = "";
52     private string _subject = "";
53     private string _subject_alt = "";
54     private string _server_cert = "";
55     private string _datetime_added = "";
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) {
62         _ca_cert = fixup(ca_cert);
63         _server_cert = fixup(server_cert);
64         _subject = fixup(subject);
65         _subject_alt = fixup(subject_alt);
66
67         // If we're reading from store, this will be overridden (see set_datetime_added)
68         _datetime_added = "";
69
70         // Work around a Portal bug that littered some credential files with this cruft.
71         string cruft = 
72 """<!-- Remove the begin and end lines from the PEM output of
73 openssl to produce this format.  Alternatively, base64 encode a DER format certificate -->""";
74         _ca_cert = _ca_cert.replace(cruft, "");
75     }
76
77     public TrustAnchor.empty() {
78     }
79
80
81     public string ca_cert {
82         get {
83             return _ca_cert;
84         }
85     }
86
87     public string subject {
88         get {
89             return _subject;
90         }
91     }
92
93     public string subject_alt  {
94         get {
95             return _subject_alt;
96         }
97     }
98
99
100     public string server_cert {
101         get {
102             return _server_cert;
103         }
104     }
105
106     public string datetime_added {
107         get {
108             return _datetime_added;
109         }
110     }
111
112     public bool is_empty() {
113         return ca_cert == "" && server_cert == "";
114     }
115
116     public TrustAnchorType get_anchor_type() {
117         return (server_cert != "" ? TrustAnchorType.SERVER_CERT 
118                 : (ca_cert != "" ? TrustAnchorType.CA_CERT : TrustAnchorType.EMPTY));
119     }
120
121     internal void set_datetime_added(string datetime) {
122         _datetime_added = fixup(datetime);
123     }
124
125     internal static string format_datetime_now() {
126         DateTime now = new DateTime.now_utc();
127         string dt = now.format("%b %d %T %Y %Z");
128         return dt;
129     }
130
131     internal void update_server_fingerprint(string fingerprint) {
132         this._server_cert = fingerprint;
133         string ta_datetime_added = TrustAnchor.format_datetime_now();
134         this.set_datetime_added(ta_datetime_added);
135     }
136
137     public int Compare(TrustAnchor other)
138     {
139         if (this.ca_cert != other.ca_cert) {
140             // IdCard.logger.trace("TrustAnchor.Compare: this.ca_cert='%s'; other.ca_cert='%s'".printf(this.ca_cert, other.ca_cert));
141             return 1;
142         }
143         if (this.subject != other.subject) {
144             // IdCard.logger.trace("TrustAnchor.Compare: this.subject='%s'; other.subject='%s'".printf(this.subject, other.subject));
145             return 1;
146         }
147         if (this.subject_alt != other.subject_alt) {
148             // IdCard.logger.trace("TrustAnchor.Compare: this.subject_alt='%s'; other.subject_alt='%s'".printf(this.subject_alt, other.subject_alt));
149             return 1;
150         }
151         if (this.server_cert != other.server_cert) {
152             // IdCard.logger.trace("TrustAnchor.Compare: this.server_cert=%s'; other.server_cert='%s'".printf(this.server_cert, other.server_cert));
153             return 1;
154         }
155
156         // Do not compare the datetime_added fields; it's not essential.
157
158         return 0;
159     }
160
161     public string? get_expiration_date(out string? err_out=null)
162     {
163         if (&err_out != null) {
164             err_out = null;
165         }
166
167         if (this.ca_cert == "") {
168             if (&err_out != null) {
169                 err_out = "Trust anchor does not have a ca_certificate";
170                 return null;
171             }
172         }
173
174         string cert = this.ca_cert;
175         cert.chomp();
176
177         uchar[] binary = Base64.decode(cert);
178         IdCard.logger.trace("get_expiration_date: encoded length=%d; decoded length=%d".printf(cert.length, binary.length));
179
180         char buf[64];
181         string err = (string) get_cert_valid_before(binary, binary.length, buf, 64);
182         if (err != "") {
183             IdCard.logger.error(@"get_expiration_date: get_cert_valid_before returned '$err'");
184             if (&err_out != null) {
185                 err_out = err;
186             }
187             return null;
188         }
189             
190         string date = (string) buf;
191         IdCard.logger.trace(@"get_expiration_date: get_cert_valid_before returned '$date'");
192
193         return date;
194     }
195 }
196
197
198 public struct Rule
199 {
200     public string pattern;
201     public string always_confirm;
202     public int Compare(Rule other) {
203         if (this.pattern != other.pattern)
204             return 1;
205         if (this.always_confirm != other.always_confirm)
206             return 1;
207         return 0;
208     }
209 }
210
211 public class IdCard : Object
212 {
213     internal static MoonshotLogger logger = get_logger("IdCard");
214
215     public const string NO_IDENTITY = "No Identity";
216
217     private string _username = "";
218     private string _issuer = "";
219
220     public string display_name { get; set; default = ""; }
221   
222     public string username { 
223         public get {
224             return _username;
225         }
226         public set {
227             _username = value;
228             update_nai();
229         }
230     }
231
232     public string issuer { 
233         public get {
234             return _issuer;
235         }
236         public set {
237             _issuer = value;
238             update_nai();
239         }
240     }
241
242     private void update_nai() {
243         _nai = username + "@" + issuer;
244     }
245
246 #if GNOME_KEYRING
247     private unowned string _password;
248     public string password {
249         get {
250             return (_password!=null) ? _password : "";
251         }
252         set {
253             if (_password != null) {
254                 GnomeKeyring.memory_free((void *)_password);
255                 _password = null;
256             }
257             if (value != null)
258                 _password = GnomeKeyring.memory_strdup(value); 
259         }
260     }
261 #else
262     public string password { get; set; default = null; }
263 #endif
264
265     private Rule[] _rules = new Rule[0];
266     public Rule[] rules {
267         get {return _rules;}
268         internal set {_rules = value ?? new Rule[0] ;}
269     }
270
271     private ArrayList<string> _services = new ArrayList<string>();
272
273     internal ArrayList<string> services {
274          get {return  _services;}
275     }
276
277     // Returns the list of services as a string, using the given separator.
278     internal string get_services_string(string sep) {
279         if (_services.is_empty) {
280             return "";
281         }
282
283         // ArrayList.to_array() seems to be unreliable -- it causes segfaults 
284         // semi-randomly. (Possibly because it returns an unowned ref?)
285         // return string.joinv(sep, _services.to_array());
286         // 
287         // This problem may be related to the one noted elsewhere as the
288         // "Centos vala array property bug".
289
290         string[] svcs = new string[_services.size];
291         for (int i = 0; i < _services.size; i++) {
292             svcs[i] = _services[i];
293         }
294
295         return string.joinv(sep, svcs);
296     }
297
298     internal void update_services(string[] services) {
299         _services.clear();
300
301         // Doesn't exist in older versions of libgee:
302         // _services.add_all_array(services);
303
304         if (services != null) {
305             foreach (string s in services) {
306                 _services.add(s);
307             }
308         }
309     } 
310
311     internal void update_services_from_list(ArrayList<string> services) {
312         if (services == this._services) {
313             // Don't try to update from self.
314             return;
315         }
316
317         _services.clear();
318
319         if (services != null) {
320             _services.add_all(services);
321         }
322     } 
323
324
325     public bool temporary {get; set; default = false; }
326
327     private TrustAnchor _trust_anchor = new TrustAnchor.empty();
328     public TrustAnchor trust_anchor  { 
329         get {
330             return _trust_anchor;
331         }
332     }
333
334     // For use by storage implementations.
335     internal void set_trust_anchor_from_store(TrustAnchor ta) {
336         _trust_anchor = ta;
337     }
338
339     internal void clear_trust_anchor() {
340         _trust_anchor = new TrustAnchor.empty();
341     }
342   
343     public string nai { public get; private set;}
344
345     public bool store_password { get; set; default = false; }
346
347     // uuid is currently used only for debugging. Must be unique, even between cards with same nai and display name.
348     public string uuid {
349         public get {return _uuid;}
350     }
351     private string _uuid = generate_uuid();
352
353     internal static string generate_uuid() {
354         uint32 rand1 = Random.next_int();
355         uint32 rand2 = Random.next_int();
356         return "%08X.%08X::%s".printf(rand1, rand2, TrustAnchor.format_datetime_now());
357     }
358
359     public bool is_no_identity() 
360     {
361         return (display_name == NO_IDENTITY);
362     }
363
364     public enum DiffFlags {
365         DISPLAY_NAME,
366         USERNAME,
367         PASSWORD,
368         ISSUER,
369         RULES,
370         SERVICES,
371         TRUST_ANCHOR;
372     }
373
374     public int Compare(IdCard other)
375     {
376         int diff = 0;
377         if (this.display_name != other.display_name)
378             diff |= 1 << DiffFlags.DISPLAY_NAME;
379
380         if (this.username != other.username)
381             diff |= 1 << DiffFlags.USERNAME;
382
383         if (this.password != other.password)
384             diff |= 1 << DiffFlags.PASSWORD;
385
386         if (this.issuer != other.issuer)
387             diff |= 1 << DiffFlags.ISSUER;
388
389         if (CompareRules(this.rules, other.rules)!=0)
390             diff |= 1 << DiffFlags.RULES;
391
392         if (CompareStringArrayList(this._services, other._services)!=0)
393             diff |= 1 << DiffFlags.SERVICES;
394
395         if (this.trust_anchor.Compare(other.trust_anchor)!=0)
396             diff |= 1 << DiffFlags.TRUST_ANCHOR;
397
398         // stdout.printf("Diff Flags: %x\n", diff);
399         if (this.display_name == other.display_name && diff != 0) {
400             logger.trace("Compare: Two IDs with display_name '%s', but diff_flags=%0x".printf(this.display_name, diff));
401         }
402         return diff;
403     }
404
405     public static IdCard NewNoIdentity() 
406     { 
407         IdCard card = new IdCard();
408         card.display_name = NO_IDENTITY;
409         card._nai = "";
410         return card;
411     }
412
413     ~IdCard() {
414         password = null;
415     }
416
417     internal void add_rule(Rule rule) {
418         _rules += rule;
419     }
420 }
421
422 public int CompareRules(Rule[] a, Rule[] b)
423 {
424     if (a.length != b.length) {
425         return 1;
426     }
427
428     for (int i = 0; i < a.length; i++) {
429         if (a[i].Compare(b[i]) != 0) {
430             return 1;
431         }
432     }
433     return 0;
434 }
435
436 public int CompareStringArrayList(ArrayList<string> a, ArrayList<string> b)
437 {
438     if (a.size != b.size) {
439         return 1;
440     }
441
442     for (int i = 0; i < a.size; i++) {
443         if (a[i] != b[i]) {
444             return 1;
445         }
446     }
447     return 0;
448 }