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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
|
# Authors:
# Endi S. Dewata <edewata@redhat.com>
#
# Copyright (C) 2015 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from __future__ import print_function
import base64
import errno
import io
import json
import logging
import os
import ssl
import tempfile
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
try:
# cryptography>=43.0.0
from cryptography.hazmat.decrepit.ciphers.algorithms import TripleDES
except ImportError:
# will be removed from this module in cryptography 48.0.0
from cryptography.hazmat.primitives.ciphers.algorithms import TripleDES
from cryptography.hazmat.primitives.padding import PKCS7
from cryptography.hazmat.primitives.serialization import (
load_pem_public_key, load_pem_private_key)
from cryptography.exceptions import InternalError as CryptographyInternalError
from ipaclient.frontend import MethodOverride
from ipalib import x509
from ipalib import constants
from ipalib.frontend import Local, Method, Object
from ipalib.util import classproperty
from ipalib import api, errors
from ipalib import Bytes, Flag, Str
from ipalib.plugable import Registry
from ipalib import _
from ipapython import ipautil
from ipapython.dnsutil import DNSName
logger = logging.getLogger(__name__)
def validated_read(argname, filename, mode='r', encoding=None):
"""Read file and catch errors
IOError and UnicodeError (for text files) are turned into a
ValidationError
"""
try:
with io.open(filename, mode=mode, encoding=encoding) as f:
data = f.read()
except IOError as exc:
raise errors.ValidationError(
name=argname,
error=_("Cannot read file '%(filename)s': %(exc)s") % {
'filename': filename, 'exc': exc.args[1]
}
)
except UnicodeError as exc:
raise errors.ValidationError(
name=argname,
error=_("Cannot decode file '%(filename)s': %(exc)s") % {
'filename': filename, 'exc': exc
}
)
return data
register = Registry()
MAX_VAULT_DATA_SIZE = 2**20 # = 1 MB
def generate_symmetric_key(password, salt):
"""
Generates symmetric key from password and salt.
"""
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=salt,
iterations=100000,
backend=default_backend()
)
return base64.b64encode(kdf.derive(password.encode('utf-8')))
def encrypt(data, symmetric_key=None, public_key=None):
"""
Encrypts data with symmetric key or public key.
"""
if symmetric_key is not None:
if public_key is not None:
raise ValueError(
"Either a symmetric or a public key is required, not both."
)
fernet = Fernet(symmetric_key)
return fernet.encrypt(data)
elif public_key is not None:
public_key_obj = load_pem_public_key(
data=public_key,
backend=default_backend()
)
return public_key_obj.encrypt(
data,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
else:
raise ValueError("Either a symmetric or a public key is required.")
def decrypt(data, symmetric_key=None, private_key=None):
"""
Decrypts data with symmetric key or public key.
"""
if symmetric_key is not None:
if private_key is not None:
raise ValueError(
"Either a symmetric or a private key is required, not both."
)
try:
fernet = Fernet(symmetric_key)
return fernet.decrypt(data)
except InvalidToken:
raise errors.AuthenticationError(
message=_('Invalid credentials'))
elif private_key is not None:
try:
private_key_obj = load_pem_private_key(
data=private_key,
password=None,
backend=default_backend()
)
return private_key_obj.decrypt(
data,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
except ValueError:
raise errors.AuthenticationError(
message=_('Invalid credentials'))
else:
raise ValueError("Either a symmetric or a private key is required.")
@register(no_fail=True)
class _fake_vault(Object):
name = 'vault'
@register(no_fail=True)
class _fake_vault_add_internal(Method):
name = 'vault_add_internal'
NO_CLI = True
@register()
class vault_add(Local):
__doc__ = _('Create a new vault.')
takes_options = (
Str(
'password?',
cli_name='password',
doc=_('Vault password'),
),
Str( # TODO: use File parameter
'password_file?',
cli_name='password_file',
doc=_('File containing the vault password'),
),
Str( # TODO: use File parameter
'public_key_file?',
cli_name='public_key_file',
doc=_('File containing the vault public key'),
),
)
@classmethod
def __NO_CLI_getter(cls):
return (api.Command.get_plugin('vault_add_internal') is
_fake_vault_add_internal)
NO_CLI = classproperty(__NO_CLI_getter)
@property
def api_version(self):
return self.api.Command.vault_add_internal.api_version
def get_args(self):
for arg in self.api.Command.vault_add_internal.args():
yield arg
for arg in super(vault_add, self).get_args():
yield arg
def get_options(self):
for option in self.api.Command.vault_add_internal.options():
if option.name not in ('ipavaultsalt', 'version'):
yield option
for option in super(vault_add, self).get_options():
yield option
def get_output_params(self):
for param in self.api.Command.vault_add_internal.output_params():
yield param
for param in super(vault_add, self).get_output_params():
yield param
def _iter_output(self):
return self.api.Command.vault_add_internal.output()
def forward(self, *args, **options):
vault_type = options.get('ipavaulttype')
if vault_type is None:
internal_cmd = self.api.Command.vault_add_internal
vault_type = internal_cmd.params.ipavaulttype.default
password = options.get('password')
password_file = options.get('password_file')
public_key = options.get('ipavaultpublickey')
public_key_file = options.get('public_key_file')
# don't send these parameters to server
if 'password' in options:
del options['password']
if 'password_file' in options:
del options['password_file']
if 'public_key_file' in options:
del options['public_key_file']
if vault_type != u'symmetric' and (password or password_file):
raise errors.MutuallyExclusiveError(
reason=_('Password can be specified only for '
'symmetric vault')
)
if vault_type != u'asymmetric' and (public_key or public_key_file):
raise errors.MutuallyExclusiveError(
reason=_('Public key can be specified only for '
'asymmetric vault')
)
if self.api.env.in_server:
backend = self.api.Backend.ldap2
else:
backend = self.api.Backend.rpcclient
if not backend.isconnected():
backend.connect()
if vault_type == u'standard':
pass
elif vault_type == u'symmetric':
# get password
if password and password_file:
raise errors.MutuallyExclusiveError(
reason=_('Password specified multiple times'))
elif password:
pass
elif password_file:
password = validated_read('password-file',
password_file,
encoding='utf-8')
password = password.rstrip('\n')
else:
password = self.api.Backend.textui.prompt_password(
'New password')
# generate vault salt
options['ipavaultsalt'] = os.urandom(16)
elif vault_type == u'asymmetric':
# get new vault public key
if public_key and public_key_file:
raise errors.MutuallyExclusiveError(
reason=_('Public key specified multiple times'))
elif public_key:
pass
elif public_key_file:
public_key = validated_read('public-key-file',
public_key_file,
mode='rb')
# store vault public key
options['ipavaultpublickey'] = public_key
else:
raise errors.ValidationError(
name='ipavaultpublickey',
error=_('Missing vault public key'))
# validate public key and prevent users from accidentally
# sending a private key to the server.
try:
load_pem_public_key(
data=public_key,
backend=default_backend()
)
except ValueError as e:
raise errors.ValidationError(
name='ipavaultpublickey',
error=_('Invalid or unsupported vault public key: %s') % e,
)
# create vault
response = self.api.Command.vault_add_internal(*args, **options)
# prepare parameters for archival
opts = options.copy()
if 'description' in opts:
del opts['description']
if 'ipavaulttype' in opts:
del opts['ipavaulttype']
if vault_type == u'symmetric':
opts['password'] = password
del opts['ipavaultsalt']
elif vault_type == u'asymmetric':
del opts['ipavaultpublickey']
# archive blank data
self.api.Command.vault_archive(*args, **opts)
return response
@register(no_fail=True)
class _fake_vault_mod_internal(Method):
name = 'vault_mod_internal'
NO_CLI = True
@register()
class vault_mod(Local):
__doc__ = _('Modify a vault.')
takes_options = (
Flag(
'change_password?',
doc=_('Change password'),
),
Str(
'old_password?',
cli_name='old_password',
doc=_('Old vault password'),
),
Str( # TODO: use File parameter
'old_password_file?',
cli_name='old_password_file',
doc=_('File containing the old vault password'),
),
Str(
'new_password?',
cli_name='new_password',
doc=_('New vault password'),
),
Str( # TODO: use File parameter
'new_password_file?',
cli_name='new_password_file',
doc=_('File containing the new vault password'),
),
Bytes(
'private_key?',
cli_name='private_key',
doc=_('Old vault private key'),
),
Str( # TODO: use File parameter
'private_key_file?',
cli_name='private_key_file',
doc=_('File containing the old vault private key'),
),
Str( # TODO: use File parameter
'public_key_file?',
cli_name='public_key_file',
doc=_('File containing the new vault public key'),
),
)
@classmethod
def __NO_CLI_getter(cls):
return (api.Command.get_plugin('vault_mod_internal') is
_fake_vault_mod_internal)
NO_CLI = classproperty(__NO_CLI_getter)
@property
def api_version(self):
return self.api.Command.vault_mod_internal.api_version
def get_args(self):
for arg in self.api.Command.vault_mod_internal.args():
yield arg
for arg in super(vault_mod, self).get_args():
yield arg
def get_options(self):
for option in self.api.Command.vault_mod_internal.options():
if option.name != 'version':
yield option
for option in super(vault_mod, self).get_options():
yield option
def get_output_params(self):
for param in self.api.Command.vault_mod_internal.output_params():
yield param
for param in super(vault_mod, self).get_output_params():
yield param
def _iter_output(self):
return self.api.Command.vault_mod_internal.output()
def forward(self, *args, **options):
vault_type = options.pop('ipavaulttype', False)
salt = options.pop('ipavaultsalt', False)
change_password = options.pop('change_password', False)
old_password = options.pop('old_password', None)
old_password_file = options.pop('old_password_file', None)
new_password = options.pop('new_password', None)
new_password_file = options.pop('new_password_file', None)
old_private_key = options.pop('private_key', None)
old_private_key_file = options.pop('private_key_file', None)
new_public_key = options.pop('ipavaultpublickey', None)
new_public_key_file = options.pop('public_key_file', None)
if self.api.env.in_server:
backend = self.api.Backend.ldap2
else:
backend = self.api.Backend.rpcclient
if not backend.isconnected():
backend.connect()
# determine the vault type based on parameters specified
if vault_type:
pass
elif change_password or new_password or new_password_file or salt:
vault_type = u'symmetric'
elif new_public_key or new_public_key_file:
vault_type = u'asymmetric'
# if vault type is specified, retrieve existing secret
if vault_type:
opts = options.copy()
opts.pop('description', None)
opts['password'] = old_password
opts['password_file'] = old_password_file
opts['private_key'] = old_private_key
opts['private_key_file'] = old_private_key_file
response = self.api.Command.vault_retrieve(*args, **opts)
data = response['result']['data']
opts = options.copy()
# if vault type is specified, update crypto attributes
if vault_type:
opts['ipavaulttype'] = vault_type
if vault_type == u'standard':
opts['ipavaultsalt'] = None
opts['ipavaultpublickey'] = None
elif vault_type == u'symmetric':
if salt:
opts['ipavaultsalt'] = salt
else:
opts['ipavaultsalt'] = os.urandom(16)
opts['ipavaultpublickey'] = None
elif vault_type == u'asymmetric':
# get new vault public key
if new_public_key and new_public_key_file:
raise errors.MutuallyExclusiveError(
reason=_('New public key specified multiple times'))
elif new_public_key:
pass
elif new_public_key_file:
new_public_key = validated_read('public_key_file',
new_public_key_file,
mode='rb')
else:
raise errors.ValidationError(
name='ipavaultpublickey',
error=_('Missing new vault public key'))
opts['ipavaultsalt'] = None
opts['ipavaultpublickey'] = new_public_key
response = self.api.Command.vault_mod_internal(*args, **opts)
# if vault type is specified, rearchive existing secret
if vault_type:
opts = options.copy()
opts.pop('description', None)
opts['data'] = data
opts['password'] = new_password
opts['password_file'] = new_password_file
opts['override_password'] = True
self.api.Command.vault_archive(*args, **opts)
return response
class _KraConfigCache:
"""The KRA config cache stores vaultconfig-show result.
"""
def __init__(self, api):
self._dirname = os.path.join(api.env.cache_dir, 'kra-config')
def _get_filename(self, domain):
basename = DNSName(domain).ToASCII() + '.json'
return os.path.join(self._dirname, basename)
def load(self, domain):
"""Load config from cache
:param domain: IPA domain
:return: dict or None
"""
filename = self._get_filename(domain)
try:
try:
with open(filename) as f:
return json.load(f)
except OSError as e:
if e.errno != errno.ENOENT:
raise
except Exception:
logger.warning("Failed to load %s", filename, exc_info=True)
return None
def store(self, domain, response):
"""Store config in cache
:param domain: IPA domain
:param config: ipa vaultconfig-show response
:return: True if config was stored successfully
"""
config = response['result'].copy()
# store certificate as PEM-encoded ASCII
config['transport_cert'] = ssl.DER_cert_to_PEM_cert(
config['transport_cert']
)
filename = self._get_filename(domain)
try:
try:
os.makedirs(self._dirname)
except EnvironmentError as e:
if e.errno != errno.EEXIST:
raise
with tempfile.NamedTemporaryFile(dir=self._dirname, delete=False,
mode='w') as f:
try:
json.dump(config, f)
ipautil.flush_sync(f)
f.close()
os.rename(f.name, filename)
except Exception:
os.unlink(f.name)
raise
except Exception:
logger.warning("Failed to save %s", filename, exc_info=True)
return False
else:
return True
def remove(self, domain):
"""Remove a config from cache, ignores errors
:param domain: IPA domain
:return: True if cert was found and removed
"""
filename = self._get_filename(domain)
try:
os.unlink(filename)
except EnvironmentError as e:
if e.errno != errno.ENOENT:
logger.warning("Failed to remove %s", filename, exc_info=True)
return False
else:
return True
_kra_config_cache = _KraConfigCache(api)
@register(override=True, no_fail=True)
class vaultconfig_show(MethodOverride):
def forward(self, *args, **options):
file = options.get('transport_out')
# don't send these parameters to server
if 'transport_out' in options:
del options['transport_out']
response = super(vaultconfig_show, self).forward(*args, **options)
# cache config
_kra_config_cache.store(self.api.env.domain, response)
if file:
with open(file, 'wb') as f:
f.write(response['result']['transport_cert'])
return response
class ModVaultData(Local):
def _generate_session_key(self, name):
if name not in constants.VAULT_WRAPPING_SUPPORTED_ALGOS:
msg = _("{algo} is not a supported vault wrapping algorithm")
raise errors.ValidationError(msg.format(algo=repr(name)))
if name == constants.VAULT_WRAPPING_AES128_CBC:
return algorithms.AES(os.urandom(128 // 8))
elif name == constants.VAULT_WRAPPING_3DES:
return TripleDES(os.urandom(196 // 8))
else:
# unreachable
raise ValueError(name)
def _get_vaultconfig(self, force_refresh=False):
config = None
if not force_refresh:
config = _kra_config_cache.load(self.api.env.domain)
if config is None:
# vaultconfig_show also caches data
response = self.api.Command.vaultconfig_show()
config = response['result']
transport_cert = x509.load_der_x509_certificate(
config['transport_cert']
)
else:
# cached JSON uses PEM-encoded ASCII string
transport_cert = x509.load_pem_x509_certificate(
config['transport_cert'].encode('ascii')
)
default_algo = config.get('wrapping_default_algorithm')
if default_algo is None:
# old server
wrapping_algo = constants.VAULT_WRAPPING_3DES
elif default_algo in constants.VAULT_WRAPPING_SUPPORTED_ALGOS:
# try to use server default
wrapping_algo = default_algo
else:
# prefer server's sorting order
for algo in config['wrapping_supported_algorithms']:
if algo in constants.VAULT_WRAPPING_SUPPORTED_ALGOS:
wrapping_algo = algo
break
else:
raise errors.ValidationError(
"No overlapping wrapping algorithm between server and "
"client."
)
return transport_cert, wrapping_algo
def _do_internal(self, algo, transport_cert, raise_unexpected,
use_oaep=False, *args, **options):
public_key = transport_cert.public_key()
# wrap session key with transport certificate
# KRA may be configured using either the default PKCS1v15 or RSA-OAEP.
# there is no way to query this info using the REST interface.
if not use_oaep:
# PKCS1v15() causes an OpenSSL exception when FIPS is enabled
# if so, we fallback to RSA-OAEP
try:
wrapped_session_key = public_key.encrypt(
algo.key,
padding.PKCS1v15()
)
except (ValueError, CryptographyInternalError):
wrapped_session_key = public_key.encrypt(
algo.key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
else:
wrapped_session_key = public_key.encrypt(
algo.key,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
options['session_key'] = wrapped_session_key
name = self.name + '_internal'
try:
# ipalib.errors.NotFound exception can be propagated
return self.api.Command[name](*args, **options)
except (errors.InternalError,
errors.ExecutionError,
errors.GenericError):
_kra_config_cache.remove(self.api.env.domain)
if raise_unexpected and use_oaep:
raise
return None
def internal(self, algo, transport_cert, *args, **options):
"""
Calls the internal counterpart of the command.
"""
# try call with cached transport certificate
try:
result = self._do_internal(algo, transport_cert, False,
False, *args, **options)
except errors.EncodingError:
result = self._do_internal(algo, transport_cert, False,
True, *args, **options)
if result is not None:
return result
# retrieve transport certificate (cached by vaultconfig_show)
transport_cert = self._get_vaultconfig(force_refresh=True)[0]
# call with the retrieved transport certificate
result = self._do_internal(algo, transport_cert, True,
False, *args, **options)
if result is not None:
return result
# call and use_oaep this time, last attempt
return self._do_internal(algo, transport_cert, True,
True, *args, **options)
@register(no_fail=True)
class _fake_vault_archive_internal(Method):
name = 'vault_archive_internal'
NO_CLI = True
@register()
class vault_archive(ModVaultData):
__doc__ = _('Archive data into a vault.')
takes_options = (
Bytes(
'data?',
doc=_('Binary data to archive'),
),
Str( # TODO: use File parameter
'in?',
doc=_('File containing data to archive'),
),
Str(
'password?',
cli_name='password',
doc=_('Vault password'),
),
Str( # TODO: use File parameter
'password_file?',
cli_name='password_file',
doc=_('File containing the vault password'),
),
Flag(
'override_password?',
doc=_('Override existing password'),
),
)
@classmethod
def __NO_CLI_getter(cls):
return (api.Command.get_plugin('vault_archive_internal') is
_fake_vault_archive_internal)
NO_CLI = classproperty(__NO_CLI_getter)
@property
def api_version(self):
return self.api.Command.vault_archive_internal.api_version
def get_args(self):
for arg in self.api.Command.vault_archive_internal.args():
yield arg
for arg in super(vault_archive, self).get_args():
yield arg
def get_options(self):
for option in self.api.Command.vault_archive_internal.options():
if option.name not in ('nonce',
'session_key',
'vault_data',
'version',
'wrapping_algo'):
yield option
for option in super(vault_archive, self).get_options():
yield option
def get_output_params(self):
for param in self.api.Command.vault_archive_internal.output_params():
yield param
for param in super(vault_archive, self).get_output_params():
yield param
def _iter_output(self):
return self.api.Command.vault_archive_internal.output()
def _wrap_data(self, algo, json_vault_data):
"""Encrypt data with wrapped session key and transport cert
:param algo: wrapping algorithm instance
:param bytes json_vault_data: dumped vault data
:return:
"""
nonce = os.urandom(algo.block_size // 8)
# wrap vault_data with session key
padder = PKCS7(algo.block_size).padder()
padded_data = padder.update(json_vault_data)
padded_data += padder.finalize()
cipher = Cipher(algo, modes.CBC(nonce), backend=default_backend())
encryptor = cipher.encryptor()
wrapped_vault_data = encryptor.update(padded_data) + encryptor.finalize()
return nonce, wrapped_vault_data
def forward(self, *args, **options):
data = options.get('data')
input_file = options.get('in')
password = options.get('password')
password_file = options.get('password_file')
override_password = options.pop('override_password', False)
# don't send these parameters to server
if 'data' in options:
del options['data']
if 'in' in options:
del options['in']
if 'password' in options:
del options['password']
if 'password_file' in options:
del options['password_file']
# get data
if data and input_file:
raise errors.MutuallyExclusiveError(
reason=_('Input data specified multiple times'))
elif data:
if len(data) > MAX_VAULT_DATA_SIZE:
raise errors.ValidationError(name="data", error=_(
"Size of data exceeds the limit. Current vault data size "
"limit is %(limit)d B")
% {'limit': MAX_VAULT_DATA_SIZE})
elif input_file:
try:
stat = os.stat(input_file)
except OSError as exc:
raise errors.ValidationError(name="in", error=_(
"Cannot read file '%(filename)s': %(exc)s")
% {'filename': input_file, 'exc': exc.args[1]})
if stat.st_size > MAX_VAULT_DATA_SIZE:
raise errors.ValidationError(name="in", error=_(
"Size of data exceeds the limit. Current vault data size "
"limit is %(limit)d B")
% {'limit': MAX_VAULT_DATA_SIZE})
data = validated_read('in', input_file, mode='rb')
else:
data = b''
if self.api.env.in_server:
backend = self.api.Backend.ldap2
else:
backend = self.api.Backend.rpcclient
if not backend.isconnected():
backend.connect()
# retrieve vault info
vault = self.api.Command.vault_show(*args, **options)['result']
vault_type = vault['ipavaulttype'][0]
if vault_type == u'standard':
encrypted_key = None
elif vault_type == u'symmetric':
# get password
if password and password_file:
raise errors.MutuallyExclusiveError(
reason=_('Password specified multiple times'))
elif password:
pass
elif password_file:
password = validated_read('password-file',
password_file,
encoding='utf-8')
password = password.rstrip('\n')
else:
if override_password:
password = self.api.Backend.textui.prompt_password(
'New password')
else:
password = self.api.Backend.textui.prompt_password(
'Password', confirm=False)
if not override_password:
# verify password by retrieving existing data
opts = options.copy()
opts['password'] = password
try:
self.api.Command.vault_retrieve(*args, **opts)
except errors.NotFound:
pass
salt = vault['ipavaultsalt'][0]
# generate encryption key from vault password
encryption_key = generate_symmetric_key(password, salt)
# encrypt data with encryption key
data = encrypt(data, symmetric_key=encryption_key)
encrypted_key = None
elif vault_type == u'asymmetric':
public_key = vault['ipavaultpublickey'][0]
# generate encryption key
encryption_key = base64.b64encode(os.urandom(32))
# encrypt data with encryption key
data = encrypt(data, symmetric_key=encryption_key)
# encrypt encryption key with public key
encrypted_key = encrypt(encryption_key, public_key=public_key)
else:
raise errors.ValidationError(
name='vault_type',
error=_('Invalid vault type'))
vault_data = {
'data': base64.b64encode(data).decode('utf-8')
}
if encrypted_key:
vault_data[u'encrypted_key'] = base64.b64encode(encrypted_key)\
.decode('utf-8')
json_vault_data = json.dumps(vault_data).encode('utf-8')
# get config
transport_cert, wrapping_algo = self._get_vaultconfig()
# let options override wrapping algo
# For backwards compatibility do not send old legacy wrapping algo
# to server. Only send the option when non-3DES is used.
wrapping_algo = options.pop('wrapping_algo', wrapping_algo)
if wrapping_algo != constants.VAULT_WRAPPING_3DES:
options['wrapping_algo'] = wrapping_algo
# generate session key
algo = self._generate_session_key(wrapping_algo)
# wrap vault data
nonce, wrapped_vault_data = self._wrap_data(algo, json_vault_data)
options.update(
nonce=nonce,
vault_data=wrapped_vault_data
)
return self.internal(algo, transport_cert, *args, **options)
@register(no_fail=True)
class _fake_vault_retrieve_internal(Method):
name = 'vault_retrieve_internal'
NO_CLI = True
@register()
class vault_retrieve(ModVaultData):
__doc__ = _('Retrieve a data from a vault.')
takes_options = (
Str(
'out?',
doc=_('File to store retrieved data'),
),
Str(
'password?',
cli_name='password',
doc=_('Vault password'),
),
Str( # TODO: use File parameter
'password_file?',
cli_name='password_file',
doc=_('File containing the vault password'),
),
Bytes(
'private_key?',
cli_name='private_key',
doc=_('Vault private key'),
),
Str( # TODO: use File parameter
'private_key_file?',
cli_name='private_key_file',
doc=_('File containing the vault private key'),
),
)
has_output_params = (
Bytes(
'data',
label=_('Data'),
),
)
@classmethod
def __NO_CLI_getter(cls):
return (api.Command.get_plugin('vault_retrieve_internal') is
_fake_vault_retrieve_internal)
NO_CLI = classproperty(__NO_CLI_getter)
@property
def api_version(self):
return self.api.Command.vault_retrieve_internal.api_version
def get_args(self):
for arg in self.api.Command.vault_retrieve_internal.args():
yield arg
for arg in super(vault_retrieve, self).get_args():
yield arg
def get_options(self):
for option in self.api.Command.vault_retrieve_internal.options():
if option.name not in ('session_key', 'version', 'wrapping_algo'):
yield option
for option in super(vault_retrieve, self).get_options():
yield option
def get_output_params(self):
for param in self.api.Command.vault_retrieve_internal.output_params():
yield param
for param in super(vault_retrieve, self).get_output_params():
yield param
def _iter_output(self):
return self.api.Command.vault_retrieve_internal.output()
def _unwrap_response(self, algo, nonce, vault_data):
cipher = Cipher(algo, modes.CBC(nonce), backend=default_backend())
# decrypt
decryptor = cipher.decryptor()
padded_data = decryptor.update(vault_data)
padded_data += decryptor.finalize()
# remove padding
unpadder = PKCS7(algo.block_size).unpadder()
json_vault_data = unpadder.update(padded_data)
json_vault_data += unpadder.finalize()
# load JSON
return json.loads(json_vault_data.decode('utf-8'))
def forward(self, *args, **options):
output_file = options.get('out')
password = options.get('password')
password_file = options.get('password_file')
private_key = options.get('private_key')
private_key_file = options.get('private_key_file')
# don't send these parameters to server
if 'out' in options:
del options['out']
if 'password' in options:
del options['password']
if 'password_file' in options:
del options['password_file']
if 'private_key' in options:
del options['private_key']
if 'private_key_file' in options:
del options['private_key_file']
if self.api.env.in_server:
backend = self.api.Backend.ldap2
else:
backend = self.api.Backend.rpcclient
if not backend.isconnected():
backend.connect()
# retrieve vault info
vault = self.api.Command.vault_show(*args, **options)['result']
vault_type = vault['ipavaulttype'][0]
# get config
transport_cert, wrapping_algo = self._get_vaultconfig()
# let options override wrapping algo
# For backwards compatibility do not send old legacy wrapping algo
# to server. Only send the option when non-3DES is used.
wrapping_algo = options.pop('wrapping_algo', wrapping_algo)
if wrapping_algo != constants.VAULT_WRAPPING_3DES:
options['wrapping_algo'] = wrapping_algo
# generate session key
algo = self._generate_session_key(wrapping_algo)
# send retrieval request to server
response = self.internal(algo, transport_cert, *args, **options)
# unwrap data with session key
vault_data = self._unwrap_response(
algo,
response['result']['nonce'],
response['result']['vault_data']
)
del algo
data = base64.b64decode(vault_data[u'data'].encode('utf-8'))
encrypted_key = None
if 'encrypted_key' in vault_data:
encrypted_key = base64.b64decode(vault_data[u'encrypted_key']
.encode('utf-8'))
if vault_type == u'standard':
pass
elif vault_type == u'symmetric':
salt = vault['ipavaultsalt'][0]
# get encryption key from vault password
if password and password_file:
raise errors.MutuallyExclusiveError(
reason=_('Password specified multiple times'))
elif password:
pass
elif password_file:
password = validated_read('password-file',
password_file,
encoding='utf-8')
password = password.rstrip('\n')
else:
password = self.api.Backend.textui.prompt_password(
'Password', confirm=False)
# generate encryption key from password
encryption_key = generate_symmetric_key(password, salt)
# decrypt data with encryption key
data = decrypt(data, symmetric_key=encryption_key)
elif vault_type == u'asymmetric':
# get encryption key with vault private key
if private_key and private_key_file:
raise errors.MutuallyExclusiveError(
reason=_('Private key specified multiple times'))
elif private_key:
pass
elif private_key_file:
private_key = validated_read('private-key-file',
private_key_file,
mode='rb')
else:
raise errors.ValidationError(
name='private_key',
error=_('Missing vault private key'))
# decrypt encryption key with private key
encryption_key = decrypt(encrypted_key, private_key=private_key)
# decrypt data with encryption key
data = decrypt(data, symmetric_key=encryption_key)
else:
raise errors.ValidationError(
name='vault_type',
error=_('Invalid vault type'))
if output_file:
with open(output_file, 'wb') as f:
f.write(data)
else:
response['result'] = {'data': data}
return response
|