Ejemplo n.º 1
0
    def create_session(self):
        desc = ua.ApplicationDescription()
        desc.ApplicationUri = self.application_uri
        desc.ProductUri = self.product_uri
        desc.ApplicationName = ua.LocalizedText(self.name)
        desc.ApplicationType = ua.ApplicationType.Client

        params = ua.CreateSessionParameters()
        nonce = utils.create_nonce(32)  # at least 32 random bytes for server to prove possession of private key (specs part 4, 5.6.2.2)
        params.ClientNonce = nonce
        params.ClientCertificate = self.security_policy.client_certificate
        params.ClientDescription = desc
        params.EndpointUrl = self.server_url.geturl()
        params.SessionName = self.description + " Session" + str(self._session_counter)
        params.RequestedSessionTimeout = 3600000
        params.MaxResponseMessageSize = 0  # means no max size
        response = self.bclient.create_session(params)
        self.security_policy.asymmetric_cryptography.verify(self.security_policy.client_certificate + nonce, response.ServerSignature.Signature)
        self._server_nonce = response.ServerNonce
        if not self.security_policy.server_certificate:
            self.security_policy.server_certificate = response.ServerCertificate
        elif self.security_policy.server_certificate != response.ServerCertificate:
            raise Exception("Server certificate mismatch")
        # remember PolicyId's: we will use them in activate_session()
        ep = Client.find_endpoint(response.ServerEndpoints, self.security_policy.Mode, self.security_policy.URI)
        self._policy_ids = ep.UserIdentityTokens
        self.session_timeout = response.RevisedSessionTimeout
        self.keepalive = KeepAlive(self, min(self.session_timeout, self.secure_channel_timeout) * 0.7)  # 0.7 is from spec
        self.keepalive.start()
        return response
Ejemplo n.º 2
0
    def create_session(self, params, sockname=None):
        self.logger.info("Create session request")

        result = ua.CreateSessionResult()
        result.SessionId = self.session_id
        result.AuthenticationToken = self.authentication_token
        result.RevisedSessionTimeout = params.RequestedSessionTimeout
        result.MaxRequestMessageSize = 65536
        self.nonce = utils.create_nonce(32)
        result.ServerNonce = self.nonce
        result.ServerEndpoints = self.get_endpoints(sockname=sockname)

        return result
Ejemplo n.º 3
0
 def _open_secure_channel(self, params):
     self.logger.info("open secure channel")
     if not self.channel or params.RequestType == ua.SecurityTokenRequestType.Issue:
         self.channel = ua.OpenSecureChannelResult()
         self.channel.SecurityToken.TokenId = 13  # random value
         self.channel.SecurityToken.ChannelId = self.iserver.get_new_channel_id()
         self.channel.SecurityToken.RevisedLifetime = params.RequestedLifetime
     self.channel.SecurityToken.TokenId += 1
     self.channel.SecurityToken.CreatedAt = datetime.utcnow()
     self.channel.SecurityToken.RevisedLifetime = params.RequestedLifetime
     self.channel.ServerNonce = utils.create_nonce(self._connection._security_policy.symmetric_key_size)
     self._connection.set_security_token(self.channel.SecurityToken)
     self._connection._security_policy.make_symmetric_key(self.channel.ServerNonce, params.ClientNonce)
     return self.channel
Ejemplo n.º 4
0
 def activate_session(self, params):
     self.logger.info("activate session")
     result = ua.ActivateSessionResult()
     if self.state != SessionState.Created:
         raise utils.ServiceError(ua.StatusCodes.BadSessionIdInvalid)
     self.nonce = utils.create_nonce(32)
     result.ServerNonce = self.nonce
     for _ in params.ClientSoftwareCertificates:
         result.Results.append(ua.StatusCode())
     self.state = SessionState.Activated
     id_token = params.UserIdentityToken
     if isinstance(id_token, ua.UserNameIdentityToken):
         if self.iserver.allow_remote_admin and id_token.UserName in ("admin", "Admin"):
             self.user = User.Admin
     return result
Ejemplo n.º 5
0
    def create_session(self):
        """
        send a CreateSessionRequest to server with reasonable parameters.
        If you want o modify settings look at code of this methods
        and make your own
        """
        desc = ua.ApplicationDescription()
        desc.ApplicationUri = self.application_uri
        desc.ProductUri = self.product_uri
        desc.ApplicationName = ua.LocalizedText(self.name)
        desc.ApplicationType = ua.ApplicationType.Client

        params = ua.CreateSessionParameters()
        nonce = utils.create_nonce(
            32
        )  # at least 32 random bytes for server to prove possession of private key (specs part 4, 5.6.2.2)
        params.ClientNonce = nonce
        params.ClientCertificate = self.security_policy.client_certificate
        params.ClientDescription = desc
        params.EndpointUrl = self.server_url.geturl()
        params.SessionName = self.description + " Session" + str(
            self._session_counter)
        params.RequestedSessionTimeout = 3600000
        params.MaxResponseMessageSize = 0  # means no max size
        response = self.uaclient.create_session(params)
        if self.security_policy.client_certificate is None:
            data = nonce
        else:
            data = self.security_policy.client_certificate + nonce
        self.security_policy.asymmetric_cryptography.verify(
            data, response.ServerSignature.Signature)
        self._server_nonce = response.ServerNonce
        if not self.security_policy.server_certificate:
            self.security_policy.server_certificate = response.ServerCertificate
        elif self.security_policy.server_certificate != response.ServerCertificate:
            raise ua.UaError("Server certificate mismatch")
        # remember PolicyId's: we will use them in activate_session()
        ep = Client.find_endpoint(response.ServerEndpoints,
                                  self.security_policy.Mode,
                                  self.security_policy.URI)
        self._policy_ids = ep.UserIdentityTokens
        self.session_timeout = response.RevisedSessionTimeout
        self.keepalive = KeepAlive(
            self,
            min(self.session_timeout, self.secure_channel_timeout) *
            0.7)  # 0.7 is from spec
        self.keepalive.start()
        return response
Ejemplo n.º 6
0
 def activate_session(self, params):
     self.logger.info("activate session")
     result = ua.ActivateSessionResult()
     if self.state != SessionState.Created:
         raise utils.ServiceError(ua.StatusCodes.BadSessionIdInvalid)
     self.nonce = utils.create_nonce(32)
     result.ServerNonce = self.nonce
     for _ in params.ClientSoftwareCertificates:
         result.Results.append(ua.StatusCode())
     self.state = SessionState.Activated
     id_token = params.UserIdentityToken
     if isinstance(id_token, ua.UserNameIdentityToken):
         if self.user_manager.check_user_token(self, id_token) == False:
             raise utils.ServiceError(ua.StatusCodes.BadUserAccessDenied)
     self.logger.info("Activated internal session %s for user %s", self.name, self.user)
     return result
Ejemplo n.º 7
0
 def activate_session(self, params):
     self.logger.info("activate session")
     result = ua.ActivateSessionResult()
     if self.state != SessionState.Created:
         raise utils.ServiceError(ua.StatusCodes.BadSessionIdInvalid)
     self.nonce = utils.create_nonce(32)
     result.ServerNonce = self.nonce
     for _ in params.ClientSoftwareCertificates:
         result.Results.append(ua.StatusCode())
     self.state = SessionState.Activated
     id_token = params.UserIdentityToken
     if isinstance(id_token, ua.UserNameIdentityToken):
         if self.iserver.allow_remote_admin and id_token.UserName in ("admin", "Admin"):
             self.user = User.Admin
     self.logger.info("Activated internal session %s for user %s", self.name, self.user)
     return result
Ejemplo n.º 8
0
 def open_secure_channel(self, renew=False):
     """
     Open secure channel, if renew is True, renew channel
     """
     params = ua.OpenSecureChannelParameters()
     params.ClientProtocolVersion = 0
     params.RequestType = ua.SecurityTokenRequestType.Issue
     if renew:
         params.RequestType = ua.SecurityTokenRequestType.Renew
     params.SecurityMode = self.security_policy.Mode
     params.RequestedLifetime = self.secure_channel_timeout
     nonce = utils.create_nonce(self.security_policy.symmetric_key_size)   # length should be equal to the length of key of symmetric encryption
     params.ClientNonce = nonce	# this nonce is used to create a symmetric key
     result = self.bclient.open_secure_channel(params)
     self.security_policy.make_symmetric_key(nonce, result.ServerNonce)
     self.secure_channel_timeout = result.SecurityToken.RevisedLifetime
Ejemplo n.º 9
0
 def open_secure_channel(self, renew=False):
     """
     Open secure channel, if renew is True, renew channel
     """
     params = ua.OpenSecureChannelParameters()
     params.ClientProtocolVersion = 0
     params.RequestType = ua.SecurityTokenRequestType.Issue
     if renew:
         params.RequestType = ua.SecurityTokenRequestType.Renew
     params.SecurityMode = self.security_policy.Mode
     params.RequestedLifetime = self.secure_channel_timeout
     nonce = utils.create_nonce(self.security_policy.symmetric_key_size)   # length should be equal to the length of key of symmetric encryption
     params.ClientNonce = nonce	# this nonce is used to create a symmetric key
     result = self.uaclient.open_secure_channel(params)
     self.security_policy.make_symmetric_key(nonce, result.ServerNonce)
     self.secure_channel_timeout = result.SecurityToken.RevisedLifetime
Ejemplo n.º 10
0
 def activate_session(self, params):
     self.logger.info("activate session")
     result = ua.ActivateSessionResult()
     if self.state != SessionState.Created:
         raise utils.ServiceError(ua.StatusCodes.BadSessionIdInvalid)
     self.nonce = utils.create_nonce(32)
     result.ServerNonce = self.nonce
     for _ in params.ClientSoftwareCertificates:
         result.Results.append(ua.StatusCode())
     self.state = SessionState.Activated
     id_token = params.UserIdentityToken
     if isinstance(id_token, ua.UserNameIdentityToken):
         if self.user_manager.check_user_token(self, id_token) == False:
             raise utils.ServiceError(ua.StatusCodes.BadUserAccessDenied)
     self.logger.info("Activated internal session %s for user %s", self.name, self.user)
     return result
Ejemplo n.º 11
0
 def _open_secure_channel(self, params):
     self.logger.info("open secure channel")
     if not self.channel or params.RequestType == ua.SecurityTokenRequestType.Issue:
         self.channel = ua.OpenSecureChannelResult()
         self.channel.SecurityToken.TokenId = 13  # random value
         self.channel.SecurityToken.ChannelId = self.iserver.get_new_channel_id(
         )
         self.channel.SecurityToken.RevisedLifetime = params.RequestedLifetime
     self.channel.SecurityToken.TokenId += 1
     self.channel.SecurityToken.CreatedAt = datetime.now()
     self.channel.SecurityToken.RevisedLifetime = params.RequestedLifetime
     self.channel.ServerNonce = utils.create_nonce(
         self._connection._security_policy.symmetric_key_size)
     self._connection.set_security_token(self.channel.SecurityToken)
     self._connection._security_policy.make_symmetric_key(
         self.channel.ServerNonce, params.ClientNonce)
     return self.channel
Ejemplo n.º 12
0
 def open(self, params, server):
     """
     called on server side to open secure channel
     """
     if not self._open or params.RequestType == auto.SecurityTokenRequestType.Issue:
         self._open = True
         self.channel = auto.OpenSecureChannelResult()
         self.channel.SecurityToken.TokenId = 13  # random value
         self.channel.SecurityToken.ChannelId = server.get_new_channel_id()
         self.channel.SecurityToken.RevisedLifetime = params.RequestedLifetime
     else:
         self._old_tokens.append(self.channel.SecurityToken.TokenId)
     self.channel.SecurityToken.TokenId += 1
     self.channel.SecurityToken.CreatedAt = datetime.utcnow()
     self.channel.SecurityToken.RevisedLifetime = params.RequestedLifetime
     self.channel.ServerNonce = utils.create_nonce(self._security_policy.symmetric_key_size)
     self._security_policy.make_symmetric_key(self.channel.ServerNonce, params.ClientNonce)
     return self.channel
Ejemplo n.º 13
0
 def open_secure_channel(self, renew=False):
     """
     Open secure channel, if renew is True, renew channel
     """
     params = ua.OpenSecureChannelParameters()
     params.ClientProtocolVersion = 0
     params.RequestType = ua.SecurityTokenRequestType.Issue
     if renew:
         params.RequestType = ua.SecurityTokenRequestType.Renew
     params.SecurityMode = self.security_policy.Mode
     params.RequestedLifetime = self.secure_channel_timeout
     # length should be equal to the length of key of symmetric encryption
     params.ClientNonce = utils.create_nonce(self.security_policy.symmetric_key_size) # this nonce is used to create a symmetric key
     result = self.uaclient.open_secure_channel(params)
     if self.secure_channel_timeout != result.SecurityToken.RevisedLifetime:
         _logger.warning("Requested secure channel timeout to be %dms, got %dms instead",
                             self.secure_channel_timeout,
                             result.SecurityToken.RevisedLifetime)
         self.secure_channel_timeout = result.SecurityToken.RevisedLifetime
Ejemplo n.º 14
0
 def open(self, params, server):
     """
     called on server side to open secure channel
     """
     if not self._open or params.RequestType == auto.SecurityTokenRequestType.Issue:
         self._open = True
         self.channel = auto.OpenSecureChannelResult()
         self.channel.SecurityToken.TokenId = 13  # random value
         self.channel.SecurityToken.ChannelId = server.get_new_channel_id()
         self.channel.SecurityToken.RevisedLifetime = params.RequestedLifetime
     else:
         self._old_tokens.append(self.channel.SecurityToken.TokenId)
     self.channel.SecurityToken.TokenId += 1
     self.channel.SecurityToken.CreatedAt = datetime.utcnow()
     self.channel.SecurityToken.RevisedLifetime = params.RequestedLifetime
     self.channel.ServerNonce = utils.create_nonce(
         self._security_policy.symmetric_key_size)
     self._security_policy.make_symmetric_key(self.channel.ServerNonce,
                                              params.ClientNonce)
     return self.channel