Ejemplo n.º 1
0
    def decrypt(self, key):
        if not self.is_encrypted:
            return False

        self.data = base64.b64encode(crypt.decrypt(self.data, key))

        return True
Ejemplo n.º 2
0
def _prompt_unencrypt_context(request,
                              ctx,
                              callback_url,
                              decode_data=True,
                              decode_render=False):
    """
    Takes care of prompting user for a password and returning an unencrypted
    version of a given context "data" section and "rendered" representation.
    Decoded data is returned as strings. No "unpickling" is performed
    """
    resp = {}
    title = "Context encrypted"
    body = "The context information you are trying to use are encrypted with " \
        "a private key. Please enter such key below to decrypt:"

    if "password" in request.POST:
        # POST already contains "unicode" data!
        pwd = request.POST["password"].encode("ascii", "ignore")
        if salt_context_key(ctx.id, pwd) == ctx.key:
            # Password is OK: decrypt
            if decode_data:
                resp["data"] = crypt.decrypt(base64.b64decode(str(ctx.data)),
                                             pwd)
            if decode_render:
                render = ContextStorage.objects.get(id=ctx.id)
                m = re.search(r"^ENCRYPTED:(.*)$", render.data)
                if m:
                    resp["render"] = crypt.decrypt(
                        base64.b64decode(str(m.group(1))), pwd)
                # Response empty in case of problems
        else:
            # Password is wrong
            resp["httpresp"] = render_password_prompt(
                request, title, body, callback_url,
                {"msg_error": "Wrong password"})
    else:
        # Prompt for password
        resp["httpresp"] = render_password_prompt(request, title, body,
                                                  callback_url)

    return resp
Ejemplo n.º 3
0
    def decrypt(self, key):
        if not self.is_encrypted:
            return False

        g = re.match(r"^ENCRYPTED:(.*)$", self.data)
        if g:
            # Warning: it does not check for password correctness!!!
            self.data = crypt.decrypt(base64.b64decode(str(g.group(1))), key)
        else:
            raise FormatError('Malformed encrypted data!')

        return True
Ejemplo n.º 4
0
def _prompt_unencrypt_context(request, ctx, callback_url, decode_data=True,
                              decode_render=False):
    """
    Takes care of prompting user for a password and returning an unencrypted
    version of a given context "data" section and "rendered" representation.
    Decoded data is returned as strings. No "unpickling" is performed
    """
    resp = {}
    title = "Context encrypted"
    body = "The context information you are trying to use are encrypted with " \
        "a private key. Please enter such key below to decrypt:"

    if "password" in request.POST:
        # POST already contains "unicode" data!
        pwd = request.POST["password"].encode("ascii", "ignore")
        if salt_context_key(ctx.id, pwd) == ctx.key:
            # Password is OK: decrypt
            if decode_data:
                resp["data"] = crypt.decrypt(
                    base64.b64decode(str(ctx.data)), pwd)
            if decode_render:
                render = ContextStorage.objects.get(id=ctx.id)
                m = re.search(r"^ENCRYPTED:(.*)$", render.data)
                if m:
                    resp["render"] = crypt.decrypt(
                        base64.b64decode(str(m.group(1))), pwd)
                # Response empty in case of problems
        else:
            # Password is wrong
            resp["httpresp"] = render_password_prompt(
                request, title, body, callback_url,
                {"msg_error": "Wrong password"}
            )
    else:
        # Prompt for password
        resp["httpresp"] = render_password_prompt(request, title, body,
                                                  callback_url)

    return resp
Ejemplo n.º 5
0
    def decrypt(self, passphrase):

        if not self.is_encrypted():
            # Not encrypted
            return False

        data_json_str = cvmo_crypt.decrypt( base64.b64decode(self.data), passphrase )
        verify_checksum = hashlib.sha1(data_json_str).hexdigest()

        if self.encryption_checksum != verify_checksum:
            raise self.CryptographyError('Wrong password')

        self.encryption_checksum = ''
        self.data = data_json_str
Ejemplo n.º 6
0
    def decrypt(self, passphrase):

        if not self.is_encrypted():
            # Not encrypted
            return False

        data_json_str = cvmo_crypt.decrypt(base64.b64decode(self.data),
                                           passphrase)
        verify_checksum = hashlib.sha1(data_json_str).hexdigest()

        if self.encryption_checksum != verify_checksum:
            raise self.CryptographyError('Wrong password')

        self.encryption_checksum = ''
        self.data = data_json_str
Ejemplo n.º 7
0
def webstart_req(request):
    """
	Request a webstart of a context/config pair
	"""

    return HttpResponse(reverse("webapi_webstart_run"))

    # Get a logger
    log = logging.getLogger("cvmo.webapi")

    # Validate request
    if not "context" in request.GET:
        log.log(logging.ERROR, "`context` is required")
        raise SuspiciousOperation("`context` is required")
    if not "config" in request.GET:
        log.log(logging.ERROR, "`config` is required")
        raise SuspiciousOperation("`config` is required")

    ############################
    # Render user data
    ############################

    # Fetch context
    try:
        ctx = ContextDefinition.objects.get(id=request.GET['context'])
    except ContextDefinition.DoesNotExist:
        raise SuspiciousOperation("`context` is required")

    # Load the rendered context
    try:
        ctx_storage = ContextStorage.objects.get(id=request.GET['context'])
        ctx_storage_data = ctx_storage.data
    except ContextStorage.DoesNotExist:
        return HttpResponse("not-found-rendered", content_type="text/plain")

    # If the context is encrypted, prompt the user
    # for the password
    if ctx.key:

        # If we have password, continue
        if "password" in request.POST:

            # POST already contains "unicode" data!
            pwd = request.POST["password"].encode("ascii", "ignore")
            if salt_context_key(ctx.id, pwd) == ctx.key:

                # Descript and un-base64
                m = re.search(r"^ENCRYPTED:(.*)$", ctx_storage_data)
                if m is None:
                    return HttpResponse("render-format-error",
                                        content_type="text/plain")
                try:
                    user_data = crypt.decrypt(
                        base64.b64decode(str(m.group(1))), pwd)
                except:
                    return HttpResponse("render-encoding-error",
                                        content_type="text/plain")

            else:

                # Render password prompt with error
                return render(
                    request, "webapi/password_prompt.html", {
                        "context": request.GET['context'],
                        "config": request.GET['config'],
                        "error": "Wrong password. Please try again"
                    })

        else:

            # Render password prompt
            return render(
                request, "webapi/password_prompt.html", {
                    "context": request.GET['context'],
                    "config": request.GET['config'],
                    "error": ""
                })

    else:

        # Un-base64
        m = re.search(r"^\s*EC2_USER_DATA\s*=\s*([^\s]*)$", ctx_storage_data,
                      re.M)
        if m is None:
            return HttpResponse("render-format-error",
                                content_type="text/plain")
        try:
            user_data = base64.b64decode(str(m.group(1)))
        except:
            return HttpResponse("render-encoding-error",
                                content_type="text/plain")

    ############################
    # Fetch WebAPI configuration
    ############################

    vm_config_id = int(request.GET['config'])
    try:
        vm_config = settings.WEBAPI_CONFIGURATIONS[vm_config_id]
    except IndexError:
        return HttpResponse("not-found-config", content_type="text/plain")

    ############################
    # Prepare VMCP One-Time Tag
    ############################

    # Create VMCP settings
    vmcp_settings = {
        'name':
        '%s-%s' % (UNSAFE_CHARS.sub("_", ctx.name), "".join([
            random.choice(string.digits + string.letters)
            for x in range(0, 10)
        ])),
        'userData':
        user_data,
        'memory':
        vm_config['memory'],
        'cpus':
        vm_config['cpus'],
        'disk':
        vm_config['disk_size'],
        'cernvmVersion':
        settings.WEBAPI_UCERNVM_VERSION,
        'flags':
        0x31
    }

    # Store json config on tag
    tag = WebAPIOneTimeTag(payload=json.dumps(vmcp_settings),
                           uuid=uuid.uuid4().hex)
    tag.save()
    # Redirect to the HTTP version of webstart_run
    return redirect("%s?tag=%s" % (reverse("webapi_webstart_run"), tag.uuid))
Ejemplo n.º 8
0
def webstart_req(request):
	"""
	Request a webstart of a context/config pair
	"""

	return HttpResponse(reverse("webapi_webstart_run"))

	# Get a logger
	log = logging.getLogger("cvmo.webapi")

	# Validate request
	if not "context" in request.GET:
		log.log(logging.ERROR, "`context` is required")
		raise SuspiciousOperation("`context` is required")
	if not "config" in request.GET:
		log.log(logging.ERROR, "`config` is required")
		raise SuspiciousOperation("`config` is required")

	############################
	# Render user data
	############################

	# Fetch context
	try:
		ctx = ContextDefinition.objects.get(id=request.GET['context'])
	except ContextDefinition.DoesNotExist:
		raise SuspiciousOperation("`context` is required")

	# Load the rendered context
	try:
		ctx_storage = ContextStorage.objects.get(id=request.GET['context'])
		ctx_storage_data = ctx_storage.data
	except ContextStorage.DoesNotExist:
		return HttpResponse("not-found-rendered",
							content_type="text/plain")

	# If the context is encrypted, prompt the user
	# for the password
	if ctx.key:

		# If we have password, continue
		if "password" in request.POST:

			# POST already contains "unicode" data!
			pwd = request.POST["password"].encode("ascii", "ignore")
			if salt_context_key(ctx.id, pwd) == ctx.key:

				# Descript and un-base64
				m = re.search(r"^ENCRYPTED:(.*)$", ctx_storage_data)
				if m is None:
					return HttpResponse("render-format-error",
										content_type="text/plain")
				try:
					user_data = crypt.decrypt(
						base64.b64decode(str(m.group(1))), pwd)
				except:
					return HttpResponse("render-encoding-error",
										content_type="text/plain")

			else:
	
				# Render password prompt with error
				return render(
					request,
					"webapi/password_prompt.html",
					{
						"context": request.GET['context'],
						"config": request.GET['config'],
						"error": "Wrong password. Please try again"
					}
				)

		else:

			# Render password prompt
			return render(
				request,
				"webapi/password_prompt.html",
				{
					"context": request.GET['context'],
					"config": request.GET['config'],
					"error": ""
				}
			)

	else:
			
		# Un-base64
		m = re.search(r"^\s*EC2_USER_DATA\s*=\s*([^\s]*)$", ctx_storage_data, re.M)
		if m is None:
			return HttpResponse("render-format-error",
								content_type="text/plain")
		try:
			user_data = base64.b64decode(str(m.group(1)))
		except:
			return HttpResponse("render-encoding-error",
								content_type="text/plain")

	############################
	# Fetch WebAPI configuration
	############################

	vm_config_id = int(request.GET['config'])
	try:
		vm_config = settings.WEBAPI_CONFIGURATIONS[vm_config_id]
	except IndexError:
		return HttpResponse("not-found-config",
							content_type="text/plain")

	############################
	# Prepare VMCP One-Time Tag
	############################

	# Create VMCP settings
	vmcp_settings = {
		'name'  		: '%s-%s' % ( UNSAFE_CHARS.sub("_", ctx.name), "".join([random.choice(string.digits + string.letters) for x in range(0,10)]) ),
		'userData' 		: user_data,
		'memory'  		: vm_config['memory'],
		'cpus' 			: vm_config['cpus'],
		'disk' 			: vm_config['disk_size'],
		'cernvmVersion'	: settings.WEBAPI_UCERNVM_VERSION,
		'flags'			: 0x31
	}

	# Store json config on tag
	tag = WebAPIOneTimeTag(
			payload=json.dumps( vmcp_settings ),
			uuid=uuid.uuid4().hex
			)
	tag.save()
	# Redirect to the HTTP version of webstart_run
	return redirect(
		"%s?tag=%s" % (reverse("webapi_webstart_run"), tag.uuid )
		)