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