Exemplo n.º 1
0
from __future__ import unicode_literals

import os
import re

from twisted.internet import defer

from ubuntu_sso import SSO_AUTH_BASE_URL
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils import compat, webclient
from ubuntu_sso.utils.webclient import restful
from ubuntu_sso.utils.webclient.common import WebClientError


logger = setup_logging("ubuntu_sso.account")
SERVICE_URL = "%s/api/1.0/" % SSO_AUTH_BASE_URL
SSO_STATUS_OK = 'ok'
SSO_STATUS_ERROR = 'error'


class InvalidEmailError(Exception):
    """The email is not valid."""


class InvalidPasswordError(Exception):
    """The password is not valid.

    Must provide at least 8 characters, one upper case, one number.
    """
Exemplo n.º 2
0
from twisted.internet import defer

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.webclient.common import (
    BaseWebClient,
    HeaderDict,
    Response,
    ProxyUnauthorizedError,
    UnauthorizedError,
    WebClientError,
)

URI_ANONYMOUS_TEMPLATE = "http://{host}:{port}/"
URI_USERNAME_TEMPLATE = "http://{username}:{password}@{host}:{port}/"

logger = setup_logging("ubuntu_sso.utils.webclient.libsoup")


class WebClient(BaseWebClient):
    """A webclient with a libsoup backend."""

    def __init__(self, *args, **kwargs):
        """Initialize this instance."""
        super(WebClient, self).__init__(*args, **kwargs)
        # pylint: disable=E0611,F0401
        from gi.repository import Soup, SoupGNOME
        self.soup = Soup
        self.session = Soup.SessionAsync()
        self.session.add_feature(SoupGNOME.ProxyResolverGNOME())
        self.session.connect("authenticate", self._on_authenticate)
Exemplo n.º 3
0
from functools import wraps

from twisted.internet import defer

from ubuntu_sso import (
    UI_EXECUTABLE_QT,
    USER_CANCELLATION,
    USER_SUCCESS,
)
from ubuntu_sso.keyring import Keyring
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils import compat, get_bin_cmd, runner


logger = setup_logging('ubuntu_sso.credentials')


APP_NAME_KEY = 'app_name'
TC_URL_KEY = 'tc_url'
HELP_TEXT_KEY = 'help_text'
WINDOW_ID_KEY = 'window_id'
PING_URL_KEY = 'ping_url'
POLICY_URL_KEY = 'policy_url'
UI_EXECUTABLE_KEY = 'ui_executable'


class CredentialsError(Exception):
    """Generic credentials error."""

Exemplo n.º 4
0
# with this program.  If not, see <http://www.gnu.org/licenses/>.
"""Main object implementations."""

import os
import sys
import warnings

from ubuntu_sso import NO_OP
from ubuntu_sso.account import Account
from ubuntu_sso.credentials import (Credentials, HELP_TEXT_KEY, PING_URL_KEY,
    TC_URL_KEY, UI_CLASS_KEY, UI_MODULE_KEY, WINDOW_ID_KEY,
    SUCCESS_CB_KEY, ERROR_CB_KEY, DENIAL_CB_KEY)
from ubuntu_sso.keyring import get_token_name, U1_APP_NAME, Keyring
from ubuntu_sso.logger import setup_logging

logger = setup_logging("ubuntu_sso.main")
U1_PING_URL = "https://one.ubuntu.com/oauth/sso-finished-so-get-tokens/"
TIMEOUT_INTERVAL = 10000  # 10 seconds


class SSOLoginProcessor(Account):
    """Login and register users using the Ubuntu Single Sign On service.

    Alias classname to maintain backwards compatibility. DO NOT USE, use
    ubuntu_sso.account.Account instead.
    """

    def __init__(self, sso_service_class=None):
        """Create a new SSO Account manager."""
        msg = 'Use ubuntu_sso.account.Account instead.'
        warnings.warn(msg, DeprecationWarning)
Exemplo n.º 5
0
)
from twisted.internet import defer

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils import get_cert_dir
from ubuntu_sso.utils.webclient.common import (
    BaseWebClient,
    HeaderDict,
    ProxyUnauthorizedError,
    Response,
    UnauthorizedError,
    WebClientError,
)
from ubuntu_sso.utils.webclient import gsettings

logger = setup_logging("ubuntu_sso.utils.webclient.qtnetwork")


def build_proxy(settings_groups):
    """Create a QNetworkProxy from these settings."""
    proxy_groups = [
        ("socks", QNetworkProxy.Socks5Proxy),
        ("https", QNetworkProxy.HttpProxy),
        ("http", QNetworkProxy.HttpProxy),
    ]
    for group, proxy_type in proxy_groups:
        if group not in settings_groups:
            continue
        settings = settings_groups[group]
        if "host" in settings and "port" in settings:
            return QNetworkProxy(proxy_type,
Exemplo n.º 6
0
"""Implementation of network state detection."""

import dbus

from twisted.internet import defer

from ubuntu_sso.networkstate import NetworkFailException
from ubuntu_sso.networkstate.networkstates import (
    ONLINE,
    OFFLINE,
    NM_STATE_CONNECTING_LIST,
    NM_STATE_CONNECTED_LIST,
    NM_STATE_DISCONNECTED_LIST,
)
from ubuntu_sso.logger import setup_logging
logger = setup_logging("ubuntu_sso.networkstate")

NM_DBUS_INTERFACE = "org.freedesktop.NetworkManager"
NM_DBUS_OBJECTPATH = "/org/freedesktop/NetworkManager"


class NetworkManagerState(object):
    """Checks the state of NetworkManager thru DBus."""
    def __init__(self, result_cb, dbus_module=dbus):
        """Initialize this instance with a result and error callbacks."""
        self.result_cb = result_cb
        self.dbus = dbus_module
        self.state_signal = None

    def call_result_cb(self, state):
        """Return the state thru the result callback."""
Exemplo n.º 7
0
from ubuntu_sso import BACKEND_EXECUTABLE
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils import get_bin_cmd
from ubuntu_sso.utils.ipc import BaseClient
from ubuntu_sso.main.perspective_broker import (
    SSO_SERVICE_NAME,
    SSOLoginClient,
    CredentialsManagementClient,
    UbuntuSSOProxyBase,
)

# Invalid name for signals that are CamelCase
# pylint: disable=C0103

logger = setup_logging("ubuntu_sso.main.darwin")
SSO_INSTALL_PATH = 'SSOInstallPath'


def get_sso_domain_socket():
    """Compute the domain socket for the sso ipc."""
    path = os.path.join(basedir.xdg_cache_home, 'sso', 'ipc')
    return path


class DescriptionFactory(object):
    """Factory that provides the server and client descriptions."""

    client_description_pattern = 'unix:path=%s'
    server_description_pattern = 'unix:%s'
Exemplo n.º 8
0
# You should have received a copy of the GNU General Public License along
# with this program.  If not, see <http://www.gnu.org/licenses/>.
"""Network state detection on OS X.

is_machine_connected(): (deferred) returns connected state as bool
NetworkManagerState: class with listening thread, calls back with state changes
"""

from twisted.internet import defer

from threading import Thread

from ubuntu_sso.networkstate import NetworkFailException
from ubuntu_sso.networkstate.networkstates import (ONLINE, OFFLINE, UNKNOWN)
from ubuntu_sso.logger import setup_logging
logger = setup_logging("ubuntu_sso.networkstate")

HOSTNAME_TO_CHECK = 'one.ubuntu.com'

from ctypes import (
    CDLL,
    POINTER,
    CFUNCTYPE,
    Structure,
    pointer,
    c_bool,
    c_long,
    c_void_p,
    c_uint32)

from ctypes.util import find_library
Exemplo n.º 9
0
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Timestamp synchronization with the server."""

import time

from twisted.internet import defer

from ubuntu_sso.logger import setup_logging

logger = setup_logging("ubuntu_sso.utils.webclient.timestamp")
NOCACHE_HEADERS = {"Cache-Control": "no-cache"}


class TimestampChecker(object):
    """A timestamp that's regularly checked with a server."""

    CHECKING_INTERVAL = 60 * 60  # in seconds
    ERROR_INTERVAL = 30  # in seconds
    SERVER_IRI = u"http://one.ubuntu.com/api/time"

    def __init__(self, webclient_class):
        """Initialize this instance."""
        self.next_check = time.time()
        self.skew = 0
        self.webclient_class = webclient_class
Exemplo n.º 10
0
from twisted.internet import defer

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.webclient.common import (
    BaseWebClient,
    HeaderDict,
    Response,
    ProxyUnauthorizedError,
    UnauthorizedError,
    WebClientError,
)

URI_ANONYMOUS_TEMPLATE = "http://{host}:{port}/"
URI_USERNAME_TEMPLATE = "http://{username}:{password}@{host}:{port}/"

logger = setup_logging("ubuntu_sso.utils.webclient.libsoup")


class WebClient(BaseWebClient):
    """A webclient with a libsoup backend."""
    def __init__(self, *args, **kwargs):
        """Initialize this instance."""
        super(WebClient, self).__init__(*args, **kwargs)
        # pylint: disable=E0611,F0401
        from gi.repository import Soup, SoupGNOME
        self.soup = Soup
        self.session = Soup.SessionAsync()
        self.session.add_feature(SoupGNOME.ProxyResolverGNOME())
        self.session.connect("authenticate", self._on_authenticate)

    def _on_message(self, session, message, d):
Exemplo n.º 11
0
    # pylint: enable=E0611,F0401
except ImportError:
    from urlparse import urlparse

from twisted.internet import defer

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.webclient.common import (
    BaseWebClient,
    HeaderDict,
    Response,
    UnauthorizedError,
    WebClientError,
)

logger = setup_logging("ubuntu_sso.utils.webclient.txweb")


class RawResponse(object):
    """A raw response from the webcall."""
    def __init__(self, headers, content, code=200, phrase="OK"):
        """Initialize this response."""
        self.headers = headers
        self.content = content
        self.code = code
        self.phrase = phrase


class WebClient(BaseWebClient):
    """A simple web client that does not support proxies, yet."""
Exemplo n.º 12
0
from ubuntu_sso import (
    DBUS_ACCOUNT_PATH,
    DBUS_BUS_NAME,
    DBUS_CREDENTIALS_IFACE,
    DBUS_CREDENTIALS_PATH,
    DBUS_IFACE_USER_NAME,
    NO_OP,
)
from ubuntu_sso.logger import setup_logging


# Disable the invalid name warning, as we have a lot of DBus style names
# pylint: disable=C0103


logger = setup_logging("ubuntu_sso.main.linux")


class SSOLoginProxy(dbus.service.Object):
    """Login thru the Single Sign On service."""

    # Use of super on an old style class
    # pylint: disable=E1002

    def __init__(self, root, *args, **kwargs):
        """Initiate the Login object."""
        # pylint: disable=E1002
        super(SSOLoginProxy, self).__init__(*args, **kwargs)
        self.root = root

    # Operator not preceded by a space (fails with dbus decorators)
Exemplo n.º 13
0
"""

from __future__ import unicode_literals

import os
import re

from twisted.internet import defer

from ubuntu_sso import SSO_AUTH_BASE_URL
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils import compat, webclient
from ubuntu_sso.utils.webclient import restful
from ubuntu_sso.utils.webclient.common import WebClientError

logger = setup_logging("ubuntu_sso.account")
SERVICE_URL = "%s/api/1.0/" % SSO_AUTH_BASE_URL
SSO_STATUS_OK = 'ok'
SSO_STATUS_ERROR = 'error'


class InvalidEmailError(Exception):
    """The email is not valid."""


class InvalidPasswordError(Exception):
    """The password is not valid.

    Must provide at least 8 characters, one upper case, one number.
    """
Exemplo n.º 14
0
    DeadReferenceError,
    NoSuchMethod,
    PBClientFactory,
    PBServerFactory,
    Referenceable,
    Root,
)

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.tcpactivation import (
    ActivationClient,
    ActivationConfig,
    ActivationInstance,
)

logger = setup_logging("ubuntu_sso.utils.ipc")
LOCALHOST = '127.0.0.1'

# pylint: disable=E1103


@defer.inlineCallbacks
def server_listen(server_factory,
                  service_name,
                  activation_cmdline,
                  description,
                  reactor=None):
    """Connect the IPC server factory."""
    config = ActivationConfig(service_name, activation_cmdline, description)
    ai = ActivationInstance(config)
    description = yield ai.get_server_description()
from twisted.internet import defer
from PyQt4 import QtGui, QtCore

from ubuntu_sso import networkstate
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.qt.sso_wizard_page import SSOWizardPage
from ubuntu_sso.qt.ui import network_detection_ui
from ubuntu_sso.utils.ui import (
    CLOSE_AND_SETUP_LATER,
    NETWORK_DETECTION_TITLE,
    NETWORK_DETECTION_WARNING,
    TRY_AGAIN_BUTTON,
)

logger = setup_logging('ubuntu_sso.network_detection_page')


class NetworkDetectionPage(SSOWizardPage):
    """Widget to show if we don't detect a network connection."""

    ui_class = network_detection_ui.Ui_Form
    connectionDetected = QtCore.pyqtSignal()

    def __init__(self, *args, **kwargs):
        super(NetworkDetectionPage, self).__init__(*args, **kwargs)
        banner_pixmap = kwargs.pop('banner_pixmap', None)
        if banner_pixmap is not None:
            self.ui.image_label.setPixmap(banner_pixmap)
        self.btn_try_again = None
Exemplo n.º 16
0
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Platform-specific translation functions."""

import gettext
import os
import sys

from ubuntu_sso.logger import setup_logging

logger = setup_logging('ubuntu_sso.utils.translation')


def _get_languages():
    """list of langs ordered by preference, or None for gettext defaults."""
    if sys.platform == 'darwin':
        from Cocoa import NSUserDefaults
        su = NSUserDefaults.standardUserDefaults()
        return su['AppleLanguages']
    else:
        if sys.platform == 'win32':
            return None
        return None


def _get_translations_data_path(fallback_path=None):
from twisted.internet import defer
from PyQt4 import QtGui, QtCore

from ubuntu_sso import networkstate
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.qt.sso_wizard_page import SSOWizardPage
from ubuntu_sso.qt.ui import network_detection_ui
from ubuntu_sso.utils.ui import (
    CLOSE_AND_SETUP_LATER,
    NETWORK_DETECTION_TITLE,
    NETWORK_DETECTION_WARNING,
    TRY_AGAIN_BUTTON,
)


logger = setup_logging('ubuntu_sso.network_detection_page')


class NetworkDetectionPage(SSOWizardPage):

    """Widget to show if we don't detect a network connection."""

    ui_class = network_detection_ui.Ui_Form
    connectionDetected = QtCore.pyqtSignal()

    def __init__(self, *args, **kwargs):
        super(NetworkDetectionPage, self).__init__(*args, **kwargs)
        banner_pixmap = kwargs.pop('banner_pixmap', None)
        if banner_pixmap is not None:
            self.ui.image_label.setPixmap(banner_pixmap)
        self.btn_try_again = None
Exemplo n.º 18
0
duplication between the different platform implementations.

"""

from twisted.internet.task import LoopingCall
from twisted.python.failure import Failure

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.ipc import (
    BaseService,
    RemoteClient,
    RemoteService,
    signal,
)

logger = setup_logging("ubuntu_sso.main.perspective_broker")
SSO_SERVICE_NAME = "ubuntu-sso-client"

# Invalid name for signals that are CamelCase
# pylint: disable=C0103


class SSOLoginProxy(RemoteService):
    """Login thru the Single Sign On service."""

    remote_calls = [
        'generate_captcha',
        'register_user',
        'login',
        'login_and_ping',
        'validate_email',
Exemplo n.º 19
0
    # pylint: enable=E0611,F0401
except ImportError:
    from urlparse import urlparse

from twisted.internet import defer

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.webclient.common import (
    BaseWebClient,
    HeaderDict,
    Response,
    UnauthorizedError,
    WebClientError,
)

logger = setup_logging("ubuntu_sso.utils.webclient.txweb")


class RawResponse(object):
    """A raw response from the webcall."""

    def __init__(self, headers, content, code=200, phrase="OK"):
        """Initialize this response."""
        self.headers = headers
        self.content = content
        self.code = code
        self.phrase = phrase


class WebClient(BaseWebClient):
    """A simple web client that does not support proxies, yet."""
Exemplo n.º 20
0
from twisted.spread.pb import (
    DeadReferenceError,
    PBClientFactory,
    Referenceable,
    Root,
)

from ubuntu_sso import NO_OP
from ubuntu_sso.account import Account
from ubuntu_sso.credentials import ERROR_KEY, ERROR_DETAIL_KEY
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.main import (CredentialsManagementRoot, SSOLoginRoot,
                             SSOCredentialsRoot, except_to_errdict)
from ubuntu_sso.utils.tcpactivation import ActivationConfig, ActivationClient

logger = setup_logging("ubuntu_sso.main.windows")
NAMED_PIPE_URL = '\\\\.\\pipe\\ubuntu_sso\\%s'
U1_REG_PATH = r'Software\Ubuntu One'
SSO_INSTALL_PATH = 'SSOInstallPath'
LOCALHOST = "127.0.0.1"
SSO_BASE_PB_PORT = 50000
SSO_RESERVED_PORTS = 3000
SSO_PORT_ALLOCATION_STEP = 3  # contiguous ports for sso, u1client, and u1cp
SSO_SERVICE_NAME = "ubuntu-sso-client"


def get_user_id():
    """Find the numeric user id."""
    process_handle = win32process.GetCurrentProcess()
    token_handle = win32security.OpenProcessToken(process_handle,
                                              win32security.TOKEN_ALL_ACCESS)
Exemplo n.º 21
0
import argparse
import os
import re

from ubuntu_sso.logger import setup_logging

from ubuntu_sso.utils.translation import get_gettext

source_path = os.path.join(os.path.dirname(__file__),
                           os.path.pardir, os.path.pardir,
                           'build', 'mo')
_ = get_gettext('ubuntu-sso-client',
                fallback_path=os.path.abspath(source_path))

logger = setup_logging('ubuntu_sso.utils.ui')


# Undefined variable '_', pylint: disable=E0602

# all the text that is used in the gui
AGREE_TO_PRIVACY_POLICY = _('By signing up to {app_name} you agree to '
    'our {privacy_policy}')
AGREE_TO_TERMS = _('By signing up to {app_name} you agree to '
    'our {terms_and_conditions}')
AGREE_TO_TERMS_AND_PRIVACY_POLICY = AGREE_TO_TERMS + _(' and {privacy_policy}')
CANCEL_BUTTON = _('Cancel')
CAPTCHA_SOLUTION_ENTRY = _('Type the characters above')
CAPTCHA_LOAD_ERROR = _('There was a problem getting the captcha, '
                       'reloading...')
CAPTCHA_RELOAD_MESSAGE = _('If you can\'t read this then %(reload_link)s '
Exemplo n.º 22
0
import socket
import sys

try:
    # pylint: disable=E0611,F0401
    from urllib.parse import quote
    # pylint: enable=E0611,F0401
except ImportError:
    from urllib import quote

from twisted.internet.defer import inlineCallbacks, returnValue

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils import compat

logger = setup_logging("ubuntu_sso.keyring")

TOKEN_SEPARATOR = ' @ '
SEPARATOR_REPLACEMENT = ' AT '

U1_APP_NAME = "Ubuntu One"
U1_KEY_NAME = "UbuntuOne token for https://ubuntuone.com"
U1_KEY_ATTR = {
    "oauth-consumer-key": "ubuntuone",
    "ubuntuone-realm": "https://ubuntuone.com",
}


def gethostname():
    """Get the hostname, return the name as unicode."""
    sys_encoding = sys.getfilesystemencoding()
Exemplo n.º 23
0
from twisted.internet import defer

from ubuntu_sso import (
    DBUS_ACCOUNT_PATH,
    DBUS_BUS_NAME,
    DBUS_CREDENTIALS_IFACE,
    DBUS_CREDENTIALS_PATH,
    DBUS_IFACE_USER_NAME,
    NO_OP,
)
from ubuntu_sso.logger import setup_logging

# Disable the invalid name warning, as we have a lot of DBus style names
# pylint: disable=C0103

logger = setup_logging("ubuntu_sso.main.linux")


class SSOLoginProxy(dbus.service.Object):
    """Login thru the Single Sign On service."""

    # Use of super on an old style class
    # pylint: disable=E1002

    def __init__(self, root, *args, **kwargs):
        """Initiate the Login object."""
        # pylint: disable=E1002
        super(SSOLoginProxy, self).__init__(*args, **kwargs)
        self.root = root

    # Operator not preceded by a space (fails with dbus decorators)
Exemplo n.º 24
0
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Utility to spawn another program from a mainloop."""

import os
import sys

from twisted.internet import utils

from ubuntu_sso.logger import setup_logging


logger = setup_logging("ubuntu_sso.utils.runner.tx")

NO_SUCH_FILE_OR_DIR = 'OSError: [Errno 2]'


EXE_EXT = ''
if sys.platform == 'win32':
    EXE_EXT = '.exe'


def spawn_program(args, reply_handler, error_handler):
    """Spawn the program specified by 'args' using the twisted reactor.

    When the program finishes, 'reply_handler' will be called with a single
    argument that will be the porgram status code.
Exemplo n.º 25
0
    QSslCertificate,
)
from twisted.internet import defer

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.webclient.common import (
    BaseWebClient,
    HeaderDict,
    ProxyUnauthorizedError,
    Response,
    UnauthorizedError,
    WebClientError,
)
from ubuntu_sso.utils.webclient import gsettings

logger = setup_logging("ubuntu_sso.utils.webclient.qtnetwork")
PROXY_REQUEST = 'https://one.ubuntu.com'


def build_proxy(settings_groups):
    """Create a QNetworkProxy from these settings."""
    proxy_groups = [
        ("socks", QNetworkProxy.Socks5Proxy),
        ("https", QNetworkProxy.HttpProxy),
        ("http", QNetworkProxy.HttpProxy),
    ]
    for group, proxy_type in proxy_groups:
        if group not in settings_groups:
            continue
        settings = settings_groups[group]
        if "host" in settings and "port" in settings:
Exemplo n.º 26
0
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Timestamp synchronization with the server."""

import time

from twisted.internet import defer

from ubuntu_sso import SSO_UONE_BASE_URL
from ubuntu_sso.logger import setup_logging

logger = setup_logging("ubuntu_sso.utils.webclient.timestamp")
NOCACHE_HEADERS = {"Cache-Control": "no-cache"}


class TimestampChecker(object):
    """A timestamp that's regularly checked with a server."""

    CHECKING_INTERVAL = 60 * 60  # in seconds
    ERROR_INTERVAL = 30  # in seconds
    SERVER_IRI = u"%s/api/time" % SSO_UONE_BASE_URL

    def __init__(self, webclient_class):
        """Initialize this instance."""
        self.next_check = time.time()
        self.skew = 0
        self.webclient_class = webclient_class
Exemplo n.º 27
0
import gtk

from dbus.mainloop.glib import DBusGMainLoop
from twisted.internet.defer import inlineCallbacks

from ubuntu_sso import (DBUS_ACCOUNT_PATH, DBUS_BUS_NAME, DBUS_IFACE_USER_NAME,
    NO_OP)
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.ui import get_data_file, _

# Instance of 'UbuntuSSOClientGUI' has no 'yyy' member
# pylint: disable=E1101


DBusGMainLoop(set_as_default=True)
logger = setup_logging('ubuntu_sso.gui')

# To be removed when Python bindings provide these constants
# as per http://code.google.com/p/pywebkitgtk/issues/detail?id=44
# WebKitLoadStatus
WEBKIT_LOAD_PROVISIONAL = 0
WEBKIT_LOAD_COMMITTED = 1
WEBKIT_LOAD_FINISHED = 2
WEBKIT_LOAD_FIRST_VISUALLY_NON_EMPTY_LAYOUT = 3
WEBKIT_LOAD_FAILED = 4
# WebKitWebNavigationReason
WEBKIT_WEB_NAVIGATION_REASON_LINK_CLICKED = 0
WEBKIT_WEB_NAVIGATION_REASON_FORM_SUBMITTED = 1
WEBKIT_WEB_NAVIGATION_REASON_BACK_FORWARD = 2
WEBKIT_WEB_NAVIGATION_REASON_RELOAD = 3
WEBKIT_WEB_NAVIGATION_REASON_FORM_RESUBMITTED = 4
Exemplo n.º 28
0
# pylint: enable=F0401

from twisted.internet import defer

from ubuntu_sso import BACKEND_EXECUTABLE
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils import get_bin_cmd
from ubuntu_sso.utils.ipc import BaseClient
from ubuntu_sso.main.perspective_broker import (
    SSO_SERVICE_NAME,
    SSOLoginClient,
    CredentialsManagementClient,
    UbuntuSSOProxyBase,
)

logger = setup_logging("ubuntu_sso.main.windows")
U1_REG_PATH = r'Software\Ubuntu One'
SSO_INSTALL_PATH = 'SSOInstallPath'
SSO_BASE_PB_PORT = 50000
SSO_RESERVED_PORTS = 3000
SSO_PORT_ALLOCATION_STEP = 3  # contiguous ports for sso, u1client, and u1cp


def get_user_id():
    """Compute the user id of the currently running process."""
    process_handle = win32process.GetCurrentProcess()
    token_handle = win32security.OpenProcessToken(
        process_handle, win32security.TOKEN_ALL_ACCESS)
    user_sid = win32security.GetTokenInformation(token_handle,
                                                 win32security.TokenUser)[0]
    sid_parts = str(user_sid).split("-")
Exemplo n.º 29
0
import cgi
import os
import sys
import time
import urllib2

from oauth import oauth
from urlparse import urlparse

from twisted.internet import defer

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils import webclient


logger = setup_logging("ubuntu_sso.utils")
BIN_SUFFIX = 'bin'
DATA_SUFFIX = 'data'

if sys.platform == "win32":
    from ubuntu_sso.utils import windows as source
else:
    from ubuntu_sso.utils import linux as source
PLATFORM_QSS = source.PLATFORM_QSS


def _get_dir(dir_name, dir_constant):
    """Return the absolute path to this project's 'dir_name' dir.

    Support symlinks, and priorize local (relative) 'dir_name' dir. If not
    found, return the value of the 'dir_constant'.
Exemplo n.º 30
0
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Implementations of different keyrings."""

import socket
import sys
import urllib

from twisted.internet.defer import inlineCallbacks, returnValue

from ubuntu_sso.logger import setup_logging

logger = setup_logging("ubuntu_sso.keyring")

TOKEN_SEPARATOR = u' @ '
SEPARATOR_REPLACEMENT = u' AT '

U1_APP_NAME = "Ubuntu One"
U1_KEY_NAME = "UbuntuOne token for https://ubuntuone.com"
U1_KEY_ATTR = {
    "oauth-consumer-key": "ubuntuone",
    "ubuntuone-realm": "https://ubuntuone.com",
}


def gethostname():
    """Get the hostname, return the name as unicode."""
    sys_encoding = sys.getfilesystemencoding()
Exemplo n.º 31
0
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Platform-specific translation functions."""

import gettext
import os
import sys

from ubuntu_sso.logger import setup_logging

logger = setup_logging('ubuntu_sso.utils.translation')


def _get_languages():
    """list of langs ordered by preference, or None for gettext defaults."""
    if sys.platform == 'darwin':
        from Cocoa import NSUserDefaults
        su = NSUserDefaults.standardUserDefaults()
        return su['AppleLanguages']
    else:
        if sys.platform == 'win32':
            return None
        return None


def _get_translations_data_path(fallback_path=None):
Exemplo n.º 32
0
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Utility to spawn another program from a mainloop."""

import os
import sys

from twisted.internet import utils

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils import compat

logger = setup_logging("ubuntu_sso.utils.runner.tx")

NO_SUCH_FILE_OR_DIR = 'OSError: [Errno 2]'

EXE_EXT = ''
if sys.platform == 'win32':
    EXE_EXT = '.exe'


def spawn_program(args, reply_handler, error_handler):
    """Spawn the program specified by 'args' using the twisted reactor.

    When the program finishes, 'reply_handler' will be called with a single
    argument that will be the porgram status code.

    If there is an error, error_handler will be called with an instance of
Exemplo n.º 33
0
import os

from httplib2 import iri2uri
from oauth import oauth
from twisted.internet import defer
from urlparse import urlparse

from ubuntu_sso import USER_SUCCESS, UI_PROXY_CREDS_DIALOG
from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.runner import spawn_program
from ubuntu_sso.utils.ui import SSL_DETAILS_TEMPLATE
from ubuntu_sso.utils.webclient.timestamp import TimestampChecker

SSL_DIALOG = 'ubuntu-sso-ssl-certificate-qt'

logger = setup_logging("ubuntu_sso.utils.webclient.common")


class WebClientError(Exception):
    """An http error happened while calling the webservice."""


class UnauthorizedError(WebClientError):
    """The request ended with bad_request, unauthorized or forbidden."""


class ProxyUnauthorizedError(WebClientError):
    """Failure raised when there is an issue with the proxy auth."""


class Response(object):
Exemplo n.º 34
0
"""Utils to be used by the UI modules."""

import argparse
import os
import re

from ubuntu_sso.logger import setup_logging

from ubuntu_sso.utils.translation import get_gettext

source_path = os.path.join(os.path.dirname(__file__), os.path.pardir,
                           os.path.pardir, 'build', 'mo')
_ = get_gettext('ubuntu-sso-client',
                fallback_path=os.path.abspath(source_path))

logger = setup_logging('ubuntu_sso.utils.ui')

# Undefined variable '_', pylint: disable=E0602

# all the text that is used in the gui
AGREE_TO_PRIVACY_POLICY = _('By signing up to {app_name} you agree to '
                            'our {privacy_policy}')
AGREE_TO_TERMS = _('By signing up to {app_name} you agree to '
                   'our {terms_and_conditions}')
AGREE_TO_TERMS_AND_PRIVACY_POLICY = AGREE_TO_TERMS + _(' and {privacy_policy}')
CANCEL_BUTTON = _('Cancel')
CAPTCHA_SOLUTION_ENTRY = _('Type the characters above')
CAPTCHA_LOAD_ERROR = _('There was a problem getting the captcha, '
                       'reloading...')
CAPTCHA_RELOAD_MESSAGE = _('If you can\'t read this then %(reload_link)s '
                           'this page')
Exemplo n.º 35
0
# individual source file, and distribute linked combinations
# including the two.
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""Retrieve the proxy configuration from Gnome."""

import subprocess

from ubuntu_sso.logger import setup_logging

logger = setup_logging("ubuntu_sso.utils.webclient.gsettings")
GSETTINGS_CMDLINE = "gsettings list-recursively org.gnome.system.proxy"
CANNOT_PARSE_WARNING = "Cannot parse gsettings value: %r"


def parse_proxy_host(hostname):
    """Parse the host to get username and password."""
    username = None
    password = None
    if "@" in hostname:
        username, hostname = hostname.rsplit("@", 1)
        if ":" in username:
            username, password = username.split(":", 1)
    return hostname, username, password

Exemplo n.º 36
0
except ImportError:
    from urllib import urlencode
    from urlparse import parse_qsl

from twisted.internet.defer import inlineCallbacks, returnValue

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils.txsecrets import SecretService
from ubuntu_sso.keyring import (
    get_token_name,
    get_old_token_name,
    U1_APP_NAME,
    try_old_credentials)


logger = setup_logging("ubuntu_sso.keyring.linux")


class Keyring(object):
    """A Keyring for a given application name."""

    def __init__(self):
        """Initialize this instance."""
        self.service = SecretService()

    @inlineCallbacks
    def _find_keyring_item(self, app_name, attr=None):
        """Return the keyring item or None if not found."""
        if attr is None:
            attr = self._get_keyring_attr(app_name)
        logger.debug("Finding all items for app_name %r.", app_name)
Exemplo n.º 37
0
import json

try:
    # pylint: disable=E0611,F0401
    from urllib.parse import urlencode
    # pylint: enable=E0611,F0401
except ImportError:
    from urllib import urlencode

from twisted.internet import defer

from ubuntu_sso.logger import setup_logging
from ubuntu_sso.utils import webclient

logger = setup_logging("ubuntu_sso.utils.webclient.restful")

POST_HEADERS = {
    "content-type": "application/x-www-form-urlencoded",
}


class RestfulClient(object):
    """A proxy-enabled restful client."""

    def __init__(self, service_iri, username=None, password=None,
                 oauth_credentials=None):
        """Initialize this instance."""
        assert service_iri.endswith("/")
        self.service_iri = service_iri
        self.webclient = webclient.webclient_factory(username=username,