forked from snowflakedb/snowflake-connector-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ocsp_snowflake.py
1760 lines (1532 loc) · 66.9 KB
/
ocsp_snowflake.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2019 Snowflake Computing Inc. All right reserved.
#
import codecs
import json
import os
import platform
import re
import sys
import tempfile
import time
import traceback
from base64 import b64decode, b64encode
from copy import deepcopy
from datetime import datetime, timedelta
from logging import getLogger
from os import environ, path
from os.path import expanduser
from threading import Lock
from time import gmtime, strftime
import jwt
import requests as generic_requests
from snowflake.connector.compat import OK, urlsplit
from snowflake.connector.constants import HTTP_HEADER_USER_AGENT
from snowflake.connector.errorcode import (
ER_INVALID_OCSP_RESPONSE,
ER_INVALID_OCSP_RESPONSE_CODE,
ER_INVALID_SSD,
ER_OCSP_FAILED_TO_CONNECT_HOST,
ER_SERVER_CERTIFICATE_REVOKED,
ER_SERVER_CERTIFICATE_UNKNOWN,
)
from snowflake.connector.errors import RevocationCheckError
from snowflake.connector.network import PYTHON_CONNECTOR_USER_AGENT
from snowflake.connector.ssd_internal_keys import (
ocsp_internal_dep1_key_ver,
ocsp_internal_dep2_key_ver,
ocsp_internal_ssd_pub_dep1,
ocsp_internal_ssd_pub_dep2,
)
from snowflake.connector.telemetry_oob import TelemetryService
from snowflake.connector.time_util import DecorrelateJitterBackoff
logger = getLogger(__name__)
class OCSPTelemetryData(object):
def __init__(self):
self.cert_id = None
self.sfc_peer_host = None
self.ocsp_url = None
self.ocsp_req = None
self.error_msg = None
self.cache_enabled = False
self.cache_hit = False
self.fail_open = False
self.insecure_mode = False
def set_cert_id(self, cert_id):
self.cert_id = cert_id
def set_sfc_peer_host(self, sfc_peer_host):
self.sfc_peer_host = sfc_peer_host
def set_ocsp_url(self, ocsp_url):
self.ocsp_url = ocsp_url
def set_ocsp_req(self, ocsp_req):
self.ocsp_req = ocsp_req
def set_error_msg(self, error_msg):
self.error_msg = error_msg
def set_cache_enabled(self, cache_enabled):
self.cache_enabled = cache_enabled
if not cache_enabled:
self.cache_hit = False
def set_cache_hit(self, cache_hit):
if not self.cache_enabled:
self.cache_hit = False
else:
self.cache_hit = cache_hit
def set_fail_open(self, fail_open):
self.fail_open = fail_open
def set_insecure_mode(self, insecure_mode):
self.insecure_mode = insecure_mode
def generate_telemetry_data(self, event_type, urgent=False):
cls, exception, stack_trace = sys.exc_info()
telemetry_data = {}
telemetry_data.update({"eventType": event_type})
telemetry_data.update({"sfcPeerHost": self.sfc_peer_host})
telemetry_data.update({"certId": self.cert_id})
telemetry_data.update({"ocspRequestBase64": self.ocsp_req})
telemetry_data.update({"ocspResponderURL": self.ocsp_url})
telemetry_data.update({"errorMessage": self.error_msg})
telemetry_data.update({"insecureMode": self.insecure_mode})
telemetry_data.update({"failOpen": self.fail_open})
telemetry_data.update({"cacheEnabled": self.cache_enabled})
telemetry_data.update({"cacheHit": self.cache_hit})
telemetry_client = TelemetryService.get_instance()
telemetry_client.log_ocsp_exception(event_type, telemetry_data, exception=str(exception),
stack_trace=traceback.format_exc(), urgent=urgent)
return telemetry_data
# To be updated once Python Driver has out of band telemetry.
# telemetry_client = TelemetryClient()
# telemetry_client.add_log_to_batch(TelemetryData(telemetry_data, datetime.utcnow()))
class SSDPubKey(object):
def __init__(self):
self._key_ver = None
self._key = None
def update(self, ssd_key_ver, ssd_key):
self._key_ver = ssd_key_ver
self._key = ssd_key
def get_key_version(self):
return self._key_ver
def get_key(self):
return self._key
class OCSPServer(object):
MAX_RETRY = int(os.getenv('OCSP_MAX_RETRY', '3'))
def __init__(self):
self.DEFAULT_CACHE_SERVER_URL = "http://ocsp.snowflakecomputing.com"
'''
The following will change to something like
http://ocspssd.snowflakecomputing.com/ocsp/
once the endpoint is up in the backend
'''
self.NEW_DEFAULT_CACHE_SERVER_BASE_URL = "https://ocspssd.snowflakecomputing.com/ocsp/"
if not OCSPServer.is_enabled_new_ocsp_endpoint():
self.CACHE_SERVER_URL = os.getenv(
"SF_OCSP_RESPONSE_CACHE_SERVER_URL",
"{}/{}".format(
self.DEFAULT_CACHE_SERVER_URL,
OCSPCache.OCSP_RESPONSE_CACHE_FILE_NAME))
else:
self.CACHE_SERVER_URL = os.getenv(
"SF_OCSP_RESPONSE_CACHE_SERVER_URL")
self.CACHE_SERVER_ENABLED = os.getenv(
"SF_OCSP_RESPONSE_CACHE_SERVER_ENABLED", "true") != "false"
# OCSP dynamic cache server URL pattern
self.OCSP_RETRY_URL = None
@staticmethod
def is_enabled_new_ocsp_endpoint():
"""
Check if new OCSP Endpoint has been
enabled
:return: True or False
"""
return os.getenv("SF_OCSP_ACTIVATE_NEW_ENDPOINT",
"false").lower() == "true"
def reset_ocsp_endpoint(self, hname):
"""
Update current object members
CACHE_SERVER_URL and RETRY_URL_PATTERN
to point to new OCSP Fetch and Retry endpoints
respectively
The new OCSP Endpoint address is based on the
hostname the customer is trying to connect to.
The deployment or in case of client failover,
the replication ID is copied from the hostname.
:param hname: hostname customer is trying to connect
to
"""
if hname.endswith("privatelink.snowflakecomputing.com"):
temp_ocsp_endpoint = "".join(["https://ocspssd.", hname, "/ocsp/"])
elif hname.endswith("global.snowflakecomputing.com"):
rep_id_begin = hname[hname.find("-"):]
temp_ocsp_endpoint = "".join(
["https://ocspssd", rep_id_begin, "/ocsp/"])
elif not hname.endswith("snowflakecomputing.com"):
temp_ocsp_endpoint = self.NEW_DEFAULT_CACHE_SERVER_BASE_URL
else:
hname_wo_acc = hname[hname.find("."):]
temp_ocsp_endpoint = "".join(
["https://ocspssd", hname_wo_acc, "/ocsp/"])
self.CACHE_SERVER_URL = "".join([temp_ocsp_endpoint, "fetch"])
self.OCSP_RETRY_URL = "".join([temp_ocsp_endpoint, "retry"])
def reset_ocsp_dynamic_cache_server_url(self, use_ocsp_cache_server):
"""
Reset OCSP dynamic cache server url pattern.
This is used only when OCSP cache server is updated.
"""
if use_ocsp_cache_server is not None:
self.CACHE_SERVER_ENABLED = use_ocsp_cache_server
if self.CACHE_SERVER_ENABLED:
logger.debug("OCSP response cache server is enabled: %s",
self.CACHE_SERVER_URL)
else:
logger.debug("OCSP response cache server is disabled")
if self.OCSP_RETRY_URL is None:
if self.CACHE_SERVER_URL is not None and \
(not self.CACHE_SERVER_URL.startswith(
self.DEFAULT_CACHE_SERVER_URL)):
# only if custom OCSP cache server is used.
parsed_url = urlsplit(
self.CACHE_SERVER_URL)
if not OCSPCache.ACTIVATE_SSD:
if parsed_url.port:
self.OCSP_RETRY_URL = \
u"{}://{}:{}/retry/".format(
parsed_url.scheme, parsed_url.hostname,
parsed_url.port) + u"{0}/{1}"
else:
self.OCSP_RETRY_URL = \
u"{}://{}/retry/".format(
parsed_url.scheme,
parsed_url.hostname) + u"{0}/{1}"
else:
if parsed_url.port:
self.OCSP_RETRY_URL = \
u"{}://{}:{}/retry".format(
parsed_url.scheme, parsed_url.hostname,
parsed_url.port)
else:
self.OCSP_RETRY_URL = \
u"{}://{}/retry".format(
parsed_url.scheme, parsed_url.hostname)
logger.debug(
"OCSP dynamic cache server RETRY URL: %s",
self.OCSP_RETRY_URL)
def download_cache_from_server(self, ocsp):
if self.CACHE_SERVER_ENABLED:
# if any of them is not cache, download the cache file from
# OCSP response cache server.
try:
retval = OCSPServer._download_ocsp_response_cache(ocsp,
self.CACHE_SERVER_URL)
if not retval:
raise RevocationCheckError(msg="OCSP Cache Server Unavailable.")
logger.debug("downloaded OCSP response cache file from %s",
self.CACHE_SERVER_URL)
logger.debug("# of certificates: %s", len(OCSPCache.CACHE))
except RevocationCheckError as rce:
logger.debug("OCSP Response cache download failed. The client"
"will reach out to the OCSP Responder directly for"
"any missing OCSP responses %s\n" % rce.msg)
@staticmethod
def _download_ocsp_response_cache(ocsp, url, do_retry=True):
"""
Download OCSP response cache from the cache server
:param url: OCSP response cache server
:param do_retry: retry if connection fails up to N times
"""
headers = {HTTP_HEADER_USER_AGENT: PYTHON_CONNECTOR_USER_AGENT}
sf_timeout = SnowflakeOCSP.OCSP_CACHE_SERVER_CONNECTION_TIMEOUT
try:
start_time = time.time()
logger.debug(
"started downloading OCSP response cache file: %s", url)
if ocsp.test_mode is not None:
test_timeout = os.getenv("SF_TEST_OCSP_CACHE_SERVER_CONNECTION_TIMEOUT", None)
sf_cache_server_url = os.getenv("SF_TEST_OCSP_CACHE_SERVER_URL", None)
if test_timeout is not None:
sf_timeout = int(test_timeout)
if sf_cache_server_url is not None:
url = sf_cache_server_url
with generic_requests.Session() as session:
max_retry = SnowflakeOCSP.OCSP_CACHE_SERVER_MAX_RETRY if do_retry else 1
sleep_time = 1
backoff = DecorrelateJitterBackoff(sleep_time, 16)
for _ in range(max_retry):
response = session.get(
url,
timeout=sf_timeout, # socket timeout
headers=headers,
)
if response.status_code == OK:
ocsp.decode_ocsp_response_cache(response.json())
elapsed_time = time.time() - start_time
logger.debug(
"ended downloading OCSP response cache file. "
"elapsed time: %ss", elapsed_time)
break
elif max_retry > 1:
sleep_time = backoff.next_sleep(1, sleep_time)
logger.debug(
"OCSP server returned %s. Retrying in %s(s)",
response.status_code, sleep_time)
time.sleep(sleep_time)
else:
logger.error(
"Failed to get OCSP response after %s attempt.",
max_retry)
return False
return True
except Exception as e:
logger.debug("Failed to get OCSP response cache from %s: %s", url,
e)
raise RevocationCheckError(
msg="Failed to get OCSP Response Cache from {}: {}".format(
url,
e),
errno=ER_OCSP_FAILED_TO_CONNECT_HOST)
def generate_get_url(self, ocsp_url, b64data):
parsed_url = urlsplit(ocsp_url)
if self.OCSP_RETRY_URL is None:
target_url = "{}/{}".format(ocsp_url, b64data)
else:
target_url = self.OCSP_RETRY_URL.format(
parsed_url.hostname, b64data)
logger.debug("OCSP Retry URL is - %s", target_url)
return target_url
class OCSPCache(object):
# Activate server side directive support
ACTIVATE_SSD = False
CACHE = {}
# OCSP cache lock
CACHE_LOCK = Lock()
# OCSP cache update flag
CACHE_UPDATED = False
# Cache Expiration in seconds (120 hours). OCSP validation cache is
# invalidated every 120 hours (5 days)
CACHE_EXPIRATION = 432000
# OCSP Response Cache URI
OCSP_RESPONSE_CACHE_URI = None
# OCSP response cache file name
OCSP_RESPONSE_CACHE_FILE_NAME = 'ocsp_response_cache.json'
# Cache directory
CACHE_DIR = None
@staticmethod
def reset_cache_dir():
# Cache directory
OCSPCache.CACHE_DIR = os.getenv('SF_OCSP_RESPONSE_CACHE_DIR')
if OCSPCache.CACHE_DIR is None:
cache_root_dir = expanduser("~") or tempfile.gettempdir()
if platform.system() == 'Windows':
OCSPCache.CACHE_DIR = path.join(cache_root_dir, 'AppData', 'Local', 'Snowflake',
'Caches')
elif platform.system() == 'Darwin':
OCSPCache.CACHE_DIR = path.join(cache_root_dir, 'Library', 'Caches', 'Snowflake')
else:
OCSPCache.CACHE_DIR = path.join(cache_root_dir, '.cache', 'snowflake')
logger.debug("cache directory: %s", OCSPCache.CACHE_DIR)
if not path.exists(OCSPCache.CACHE_DIR):
try:
os.makedirs(OCSPCache.CACHE_DIR, mode=0o700)
except Exception as ex:
logger.debug('cannot create a cache directory: [%s], err=[%s]',
OCSPCache.CACHE_DIR, ex)
OCSPCache.CACHE_DIR = None
@staticmethod
def del_cache_file():
"""
Delete the OCSP response cache file if exists
"""
cache_file = path.join(OCSPCache.CACHE_DIR, OCSPCache.OCSP_RESPONSE_CACHE_FILE_NAME)
if path.exists(cache_file):
os.unlink(cache_file)
@staticmethod
def set_ssd_status(ssd_status):
OCSPCache.ACTIVATE_SSD = ssd_status
@staticmethod
def reset_ocsp_response_cache_uri(
ocsp_response_cache_uri):
if ocsp_response_cache_uri is None and OCSPCache.CACHE_DIR is not None:
OCSPCache.OCSP_RESPONSE_CACHE_URI = 'file://' + path.join(
OCSPCache.CACHE_DIR,
OCSPCache.OCSP_RESPONSE_CACHE_FILE_NAME)
else:
OCSPCache.OCSP_RESPONSE_CACHE_URI = ocsp_response_cache_uri
if OCSPCache.OCSP_RESPONSE_CACHE_URI is not None:
# normalize URI for Windows
OCSPCache.OCSP_RESPONSE_CACHE_URI = \
OCSPCache.OCSP_RESPONSE_CACHE_URI.replace('\\', '/')
logger.debug("ocsp_response_cache_uri: %s",
OCSPCache.OCSP_RESPONSE_CACHE_URI)
logger.debug(
"OCSP_VALIDATION_CACHE size: %s", len(OCSPCache.CACHE))
@staticmethod
def read_file(ocsp):
"""
Read OCSP Response cache data from the URI, which is very likely a file.
"""
try:
parsed_url = urlsplit(OCSPCache.OCSP_RESPONSE_CACHE_URI)
if parsed_url.scheme == 'file':
OCSPCache.read_ocsp_response_cache_file(
ocsp,
path.join(parsed_url.netloc, parsed_url.path))
else:
raise Exception(
"Unsupported OCSP URI: %s",
OCSPCache.OCSP_RESPONSE_CACHE_URI)
except Exception as e:
logger.debug(
"Failed to read OCSP response cache file %s: %s, "
"No worry. It will validate with OCSP server. "
"Ignoring...",
OCSPCache.OCSP_RESPONSE_CACHE_URI, e, exc_info=True)
@staticmethod
def read_ocsp_response_cache_file(ocsp, filename):
"""
Reads OCSP Response cache
"""
try:
if OCSPCache.check_ocsp_response_cache_lock_dir(filename) and \
path.exists(filename):
with codecs.open(filename, 'r', encoding='utf-8',
errors='ignore') as f:
ocsp.decode_ocsp_response_cache(json.load(f))
logger.debug("Read OCSP response cache file: %s, count=%s",
filename, len(OCSPCache.CACHE))
else:
logger.debug(
"Failed to locate OCSP response cache file. "
"No worry. It will validate with OCSP server: %s",
filename
)
except Exception as ex:
logger.debug("Caught - %s", ex)
raise ex
@staticmethod
def update_file(ocsp):
"""
Update OCSP Respone Cache file
"""
with OCSPCache.CACHE_LOCK:
if OCSPCache.CACHE_UPDATED:
OCSPCache.update_ocsp_response_cache_file(
ocsp,
OCSPCache.OCSP_RESPONSE_CACHE_URI)
OCSPCache.CACHE_UPDATED = False
@staticmethod
def update_ocsp_response_cache_file(ocsp, ocsp_response_cache_uri):
"""
Updates OCSP Response Cache
"""
if ocsp_response_cache_uri is not None:
try:
parsed_url = urlsplit(ocsp_response_cache_uri)
if parsed_url.scheme == 'file':
filename = path.join(parsed_url.netloc, parsed_url.path)
lock_dir = filename + '.lck'
for _ in range(100):
# wait until the lck file has been removed
# or up to 1 second (0.01 x 100)
if OCSPCache.lock_cache_file(lock_dir):
break
time.sleep(0.01)
try:
OCSPCache.write_ocsp_response_cache_file(
ocsp,
filename)
finally:
OCSPCache.unlock_cache_file(lock_dir)
else:
logger.debug(
"No OCSP response cache file is written, because the "
"given URI is not a file: %s. Ignoring...",
ocsp_response_cache_uri)
except Exception as e:
logger.debug(
"Failed to write OCSP response cache "
"file. file: %s, error: %s, Ignoring...",
ocsp_response_cache_uri, e, exc_info=True)
@staticmethod
def write_ocsp_response_cache_file(ocsp, filename):
"""
Writes OCSP Response Cache
"""
logger.debug('writing OCSP response cache file')
file_cache_data = {}
ocsp.encode_ocsp_response_cache(file_cache_data)
with codecs.open(filename, 'w', encoding='utf-8', errors='ignore') as f:
json.dump(file_cache_data, f)
@staticmethod
def check_ocsp_response_cache_lock_dir(filename):
"""
Checks if the lock directory exists. True if it can update the cache
file or False when some other process may be updating the cache file.
"""
current_time = int(time.time())
lock_dir = filename + '.lck'
try:
ts_cache_file = OCSPCache._file_timestamp(filename)
if not path.exists(lock_dir) and \
current_time - OCSPCache.CACHE_EXPIRATION <= ts_cache_file:
# use cache only if no lock directory exists and the cache file
# was created last 24 hours
return True
if path.exists(lock_dir):
# delete lock directory if older 60 seconds
ts_lock_dir = OCSPCache._file_timestamp(lock_dir)
if ts_lock_dir < current_time - 60:
OCSPCache.unlock_cache_file(lock_dir)
logger.debug(
"The lock directory is older than 60 seconds. "
"Deleted the lock directory and ignoring the cache: %s",
lock_dir
)
else:
logger.debug(
'The lock directory exists. Other process may be '
'updating the cache file: %s, %s', filename, lock_dir)
else:
os.unlink(filename)
logger.debug(
"The cache is older than 1 day. "
"Deleted the cache file: %s", filename)
except Exception as e:
logger.debug(
"Failed to check OCSP response cache file. No worry. It will "
"validate with OCSP server: file: %s, lock directory: %s, "
"error: %s", filename, lock_dir, e)
return False
@staticmethod
def is_cache_fresh(current_time, ts):
return current_time - OCSPCache.CACHE_EXPIRATION <= ts
@staticmethod
def find_cache(ocsp, cert_id, subject):
subject_name = ocsp.subject_name(subject) if subject else None
current_time = int(time.time())
hkey = ocsp.decode_cert_id_key(cert_id)
if hkey in OCSPCache.CACHE:
ts, cache = OCSPCache.CACHE[hkey]
try:
# is_valid_time can raise exception if the cache
# entry is a SSD.
if OCSPCache.is_cache_fresh(current_time, ts) and \
ocsp.is_valid_time(cert_id, cache):
if subject_name:
logger.debug('hit cache for subject: %s', subject_name)
return True, cache
else:
OCSPCache.delete_cache(ocsp, cert_id)
except Exception as ex:
if OCSPCache.ACTIVATE_SSD:
logger.debug(
"Potentially tried to validate SSD as OCSP Response."
"Attempting to validate as SSD", ex)
try:
if OCSPCache.is_cache_fresh(current_time, ts) and \
SFSsd.validate(cache):
if subject_name:
logger.debug('hit cache for subject: %s',
subject_name)
return True, cache
else:
OCSPCache.delete_cache(ocsp, cert_id)
except Exception:
OCSPCache.delete_cache(ocsp, cert_id)
else:
logger.debug("Could not validate cache entry %s %s",
cert_id, ex)
OCSPCache.CACHE_UPDATED = True
if subject_name:
logger.debug('not hit cache for subject: %s', subject_name)
return False, None
@staticmethod
def update_or_delete_cache(ocsp, cert_id, ocsp_response, ts):
try:
current_time = int(time.time())
found, _ = OCSPCache.find_cache(ocsp, cert_id, None)
if current_time - OCSPCache.CACHE_EXPIRATION <= ts:
# creation time must be new enough
OCSPCache.update_cache(ocsp, cert_id, ocsp_response)
elif found:
# invalidate the cache if exists
OCSPCache.delete_cache(ocsp, cert_id)
except Exception as ex:
logger.debug("Caught here > %s", ex)
raise ex
@staticmethod
def iterate_cache():
for rec in OCSPCache.CACHE.items():
yield rec
@staticmethod
def update_cache(ocsp, cert_id, ocsp_response):
# Every time this is called the in memory cache will
# be updated and written to disk.
current_time = int(time.time())
with OCSPCache.CACHE_LOCK:
hkey = ocsp.decode_cert_id_key(cert_id)
OCSPCache.CACHE[hkey] = (current_time, ocsp_response)
OCSPCache.CACHE_UPDATED = True
@staticmethod
def delete_cache(ocsp, cert_id):
try:
with OCSPCache.CACHE_LOCK:
hkey = ocsp.decode_cert_id_key(cert_id)
if hkey in OCSPCache.CACHE:
del OCSPCache.CACHE[hkey]
OCSPCache.CACHE_UPDATED = True
except Exception as ex:
logger.debug("Could not acquire lock", ex)
@staticmethod
def merge_cache(ocsp, previous_cache_filename, current_cache_filename,
output_filename):
"""
Merge two cache files into one cache and save to the output.
current_cache takes precedence over previous_cache.
"""
OCSPCache.clear_cache()
if previous_cache_filename:
OCSPCache.read_ocsp_response_cache_file(
ocsp, previous_cache_filename)
previous_cache = deepcopy(OCSPCache.CACHE)
OCSPCache.clear_cache()
OCSPCache.read_ocsp_response_cache_file(ocsp, current_cache_filename)
current_cache = deepcopy(OCSPCache.CACHE)
# overwrite the previous one with the current one
previous_cache.update(current_cache)
OCSPCache.CACHE = previous_cache
OCSPCache.write_ocsp_response_cache_file(ocsp, output_filename)
@staticmethod
def _file_timestamp(filename):
"""
Last created timestamp of the file/dir
"""
if platform.system() == 'Windows':
ts = int(path.getctime(filename))
else:
stat = os.stat(filename)
if hasattr(stat, 'st_birthtime'): # odx
ts = int(stat.st_birthtime)
else:
ts = int(stat.st_mtime) # linux
return ts
@staticmethod
def lock_cache_file(fname):
"""
Lock a cache file by creating a directory.
"""
try:
os.mkdir(fname)
return True
except IOError:
return False
@staticmethod
def unlock_cache_file(fname):
"""
Unlock a cache file by deleting a directory
"""
try:
os.rmdir(fname)
return True
except IOError:
return False
@staticmethod
def delete_cache_file():
"""
Delete the cache file. Used by tests only
"""
parsed_url = urlsplit(OCSPCache.OCSP_RESPONSE_CACHE_URI)
fname = path.join(parsed_url.netloc, parsed_url.path)
OCSPCache.lock_cache_file(fname)
try:
os.unlink(fname)
finally:
OCSPCache.unlock_cache_file(fname)
@staticmethod
def clear_cache():
"""
Clear cache
"""
with OCSPCache.CACHE_LOCK:
OCSPCache.CACHE = {}
@staticmethod
def cache_size():
"""
Cache size
"""
with OCSPCache.CACHE_LOCK:
return len(OCSPCache.CACHE)
# Reset OCSP cache directory
OCSPCache.reset_cache_dir()
class SFSsd(object):
# Support for Server Side Directives
ACTIVATE_SSD = False
# SSD Cache
SSD_CACHE = {}
# SSD Cache Lock
SSD_CACHE_LOCK = Lock()
# In memory public keys
ssd_pub_key_dep1 = SSDPubKey()
ssd_pub_key_dep2 = SSDPubKey()
SSD_ROOT_DIR = os.getenv('SF_OCSP_SSD_DIR') or \
expanduser("~") or tempfile.gettempdir()
if platform.system() == 'Windows':
SSD_DIR = path.join(SSD_ROOT_DIR, 'AppData', 'Local', 'Snowflake',
'Caches')
elif platform.system() == 'Darwin':
SSD_DIR = path.join(SSD_ROOT_DIR, 'Library', 'Caches', 'Snowflake')
else:
SSD_DIR = path.join(SSD_ROOT_DIR, '.cache', 'snowflake')
def __init__(self):
SFSsd.ssd_pub_key_dep1.update(ocsp_internal_dep1_key_ver,
ocsp_internal_ssd_pub_dep1)
SFSsd.ssd_pub_key_dep2.update(ocsp_internal_dep2_key_ver,
ocsp_internal_ssd_pub_dep2)
@staticmethod
def check_ssd_support():
# Activate server side directive support
SFSsd.ACTIVATE_SSD = os.getenv("SF_OCSP_ACTIVATE_SSD",
"false").lower() == "true"
@staticmethod
def add_to_ssd_persistent_cache(hostname, ssd):
with SFSsd.SSD_CACHE_LOCK:
SFSsd.SSD_CACHE[hostname] = ssd
@staticmethod
def remove_from_ssd_persistent_cache(hostname):
with SFSsd.SSD_CACHE_LOCK:
if hostname in SFSsd.SSD_CACHE:
del SFSsd.SSD_CACHE[hostname]
@staticmethod
def clear_ssd_cache():
with SFSsd.SSD_CACHE_LOCK:
SFSsd.SSD_CACHE = {}
@staticmethod
def find_in_ssd_cache(account_name):
if account_name in SFSsd.SSD_CACHE:
return True, SFSsd.SSD_CACHE[account_name]
return False, None
@staticmethod
def ret_ssd_pub_key(iss_name):
if iss_name == 'dep1':
return SFSsd.ssd_pub_key_dep1.get_key()
elif iss_name == 'dep2':
return SFSsd.ssd_pub_key_dep2.get_key()
else:
return None
@staticmethod
def ret_ssd_pub_key_ver(iss_name):
if iss_name == 'dep1':
return SFSsd.ssd_pub_key_dep1.get_key_version()
elif iss_name == 'dep2':
return SFSsd.ssd_pub_key_dep2.get_key_version()
else:
return None
@staticmethod
def update_pub_key(ssd_issuer, ssd_pub_key_ver, ssd_pub_key_new):
if ssd_issuer == 'dep1':
SFSsd.ssd_pub_key_dep1.update(ssd_pub_key_ver, ssd_pub_key_new)
elif ssd_issuer == 'dep2':
SFSsd.ssd_pub_key_dep2.update(ssd_pub_key_ver, ssd_pub_key_new)
@staticmethod
def validate(ssd):
try:
ssd_header = jwt.get_unverified_header(ssd)
jwt.decode(ssd, SFSsd.ret_ssd_pub_key(ssd_header['ssd_iss']),
algorithm='RS512')
except Exception as ex:
logger.debug("Error while validating SSD Token", ex)
return False
return True
class SnowflakeOCSP(object):
"""
OCSP validator using PyOpenSSL and asn1crypto/pyasn1
"""
# root certificate cache
ROOT_CERTIFICATES_DICT = {} # root certificates
# root certificate cache lock
ROOT_CERTIFICATES_DICT_LOCK = Lock()
# ssd cache object
SSD = SFSsd()
# cache object
OCSP_CACHE = OCSPCache()
OCSP_WHITELIST = re.compile(
r'^'
r'(.*\.snowflakecomputing\.com$'
r'|(?:|.*\.)s3.*\.amazonaws\.com$' # start with s3 or .s3 in the middle
r'|.*\.okta\.com$'
r'|(?:|.*\.)storage\.googleapis\.com$'
r'|.*\.blob\.core\.windows\.net$'
r'|.*\.blob\.core\.usgovcloudapi\.net$)')
# Tolerable validity date range ratio. The OCSP response is valid up
# to (next update timestap) + (next update timestamp -
# this update timestap) * TOLERABLE_VALIDITY_RANGE_RATIO. This buffer
# yields some time for Root CA to update intermediate CA's certificate
# OCSP response. In fact, they don't update OCSP response in time. In Dec
# 2016, they left OCSP response expires for 5 hours at least, and it
# caused the connectivity issues in customers.
# With this buffer, about 2 days are given for 180 days validity date.
TOLERABLE_VALIDITY_RANGE_RATIO = 0.01
# Maximum clock skew in seconds (15 minutes) allowed when checking
# validity of OCSP responses
MAX_CLOCK_SKEW = 900
# Epoch time
ZERO_EPOCH = datetime.utcfromtimestamp(0)
# Timestamp format for logging
OUTPUT_TIMESTAMP_FORMAT = '%Y-%m-%d %H:%M:%SZ'
# Connection timeout in seconds for CA OCSP Responder
CA_OCSP_RESPONDER_CONNECTION_TIMEOUT = 10
# Connection timeout in seconds for Cache Server
OCSP_CACHE_SERVER_CONNECTION_TIMEOUT = 5
# MAX number of connection retry attempts with Responder in Fail Open
CA_OCSP_RESPONDER_MAX_RETRY_FO = 1
# MAX number of connection retry attempts with Responder in Fail Close
CA_OCSP_RESPONDER_MAX_RETRY_FC = 3
# MAX number of connection retry attempts with Cache Server
OCSP_CACHE_SERVER_MAX_RETRY = 1
def __init__(
self,
ocsp_response_cache_uri=None,
use_ocsp_cache_server=None,
use_post_method=True,
use_fail_open=True):
self.test_mode = os.getenv("SF_OCSP_TEST_MODE", None)
if self.test_mode == 'true':
logger.debug("WARNING - DRIVER CONFIGURED IN TEST MODE")
self._use_post_method = use_post_method
SnowflakeOCSP.SSD.check_ssd_support()
self.OCSP_CACHE_SERVER = OCSPServer()
self.debug_ocsp_failure_url = None
if os.getenv("SF_OCSP_FAIL_OPEN") is not None:
# failOpen Env Variable is for internal usage/ testing only.
# Using it in production is not advised and not supported.
self.FAIL_OPEN = os.getenv("SF_OCSP_FAIL_OPEN").lower() == 'true'
else:
self.FAIL_OPEN = use_fail_open
if SnowflakeOCSP.SSD.ACTIVATE_SSD:
SnowflakeOCSP.OCSP_CACHE.set_ssd_status(
SnowflakeOCSP.SSD.ACTIVATE_SSD)
SnowflakeOCSP.SSD.clear_ssd_cache()
SnowflakeOCSP.read_directives()
SnowflakeOCSP.OCSP_CACHE.reset_ocsp_response_cache_uri(
ocsp_response_cache_uri)
if not OCSPServer.is_enabled_new_ocsp_endpoint():
self.OCSP_CACHE_SERVER.reset_ocsp_dynamic_cache_server_url(
use_ocsp_cache_server)
SnowflakeOCSP.OCSP_CACHE.read_file(self)
def validate_certfile(self, cert_filename, no_exception=False):
"""
Validates the certificate is NOT revoked
"""
cert_map = {}
telemetry_data = OCSPTelemetryData()
telemetry_data.set_cache_enabled(self.OCSP_CACHE_SERVER.CACHE_SERVER_ENABLED)
telemetry_data.set_insecure_mode(False)
telemetry_data.set_sfc_peer_host(cert_filename)
telemetry_data.set_fail_open(self.is_enabled_fail_open())
try:
self.read_cert_bundle(cert_filename, cert_map)
cert_data = self.create_pair_issuer_subject(cert_map)
except Exception as ex:
logger.debug("Caught exception while validating certfile %s", str(ex))
raise ex
return self._validate(
None, cert_data, telemetry_data, do_retry=False, no_exception=no_exception)
def validate(self, hostname, connection, no_exception=False):
"""
Validates the certificate is not revoked using OCSP
"""
logger.debug(u'validating certificate: %s', hostname)
do_retry = SnowflakeOCSP.get_ocsp_retry_choice()
m = not SnowflakeOCSP.OCSP_WHITELIST.match(hostname)
if m or hostname.startswith("ocspssd"):
logger.debug(u'skipping OCSP check: %s', hostname)
return [None, None, None, None, None]
if OCSPServer.is_enabled_new_ocsp_endpoint():
self.OCSP_CACHE_SERVER.reset_ocsp_endpoint(hostname)
telemetry_data = OCSPTelemetryData()
telemetry_data.set_cache_enabled(self.OCSP_CACHE_SERVER.CACHE_SERVER_ENABLED)
telemetry_data.set_insecure_mode(False)
telemetry_data.set_sfc_peer_host(hostname)
telemetry_data.set_fail_open(self.is_enabled_fail_open())
try:
cert_data = self.extract_certificate_chain(connection)
except RevocationCheckError:
logger.debug(telemetry_data.generate_telemetry_data("RevocationCheckFailure"))
return None
return self._validate(hostname, cert_data, telemetry_data, do_retry, no_exception)
def _validate(
self, hostname, cert_data, telemetry_data, do_retry=True, no_exception=False):
# Validate certs sequentially if OCSP response cache server is used