Commit 41e7cb38 authored by Stef Walter's avatar Stef Walter Committed by Stef Walter
Browse files

Complete Service instantiation, add mock service, and initial test

 * Not yet tested, but compiles
parent 8a6ba782
......@@ -2,6 +2,7 @@
*.o
*.la
*.lo
*.pyc
.deps
.cproject
.libs
......@@ -27,3 +28,5 @@ stamp*
.cproject
/po/POTFILES
/library/tests/test-session
......@@ -165,10 +165,11 @@ on_service_ensure_session (GObject *source, GAsyncResult *result, gpointer user_
GSimpleAsyncResult *res = G_SIMPLE_ASYNC_RESULT (user_data);
GSecretItem *self = GSECRET_ITEM (g_async_result_get_source_object (user_data));
GError *error = NULL;
GCancellable *cancellable = NULL;
const gchar *session_path;
session_path = gsecret_service_ensure_session_finish (self->pv->service,
result, &error);
session_path = _gsecret_service_ensure_session_finish (self->pv->service,
result, &cancellable, &error);
if (error != NULL) {
g_simple_async_result_take_error (res, error);
g_simple_async_result_complete (res);
......@@ -177,11 +178,11 @@ on_service_ensure_session (GObject *source, GAsyncResult *result, gpointer user_
g_assert (session_path != NULL && session_path[0] != '\0');
g_dbus_proxy_call (G_DBUS_PROXY (self), "GetSecret",
g_variant_new ("o", session_path),
G_DBUS_CALL_FLAGS_NONE, -1,
_gsecret_async_result_get_cancellable (res),
G_DBUS_CALL_FLAGS_NONE, -1, cancellable,
on_item_get_secret_ready, g_object_ref (res));
}
g_clear_object (&cancellable);
g_object_unref (res);
}
......
......@@ -20,22 +20,29 @@
G_BEGIN_DECLS
#define GSECRET_SERVICE_PATH "/org/freedesktop/secrets"
#define GSECRET_SERVICE_BUS_NAME "org.freedesktop.Secret.Service"
#define GSECRET_SERVICE_INTERFACE "org.freedesktop.Secret.Service"
#define GSECRET_COLLECTION_INTERFACE "org.freedesktop.Secret.Collection"
gchar * _gsecret_util_parent_path (const gchar *path);
GSecretService * _gsecret_service_bare_instance (GDBusConnection *connection,
const gchar *bus_name);
GVariant * _gsecret_service_encode_secret (GSecretService *self,
GSecretValue *value);
GSecretValue * _gsecret_service_decode_secret (GSecretService *service,
GVariant *encoded);
GCancellable * _gsecret_async_result_get_cancellable (GSimpleAsyncResult *result);
void _gsecret_async_result_set_cancellable (GSimpleAsyncResult *result,
GCancellable *cancellable);
gboolean _gsecret_async_result_propagate_cancelled (GSimpleAsyncResult *result);
const gchar * _gsecret_service_ensure_session_finish (GSecretService *self,
GAsyncResult *result,
GCancellable **cancellable,
GError **error);
G_END_DECLS
......
......@@ -49,6 +49,11 @@ struct _GSecretServicePrivate {
gpointer session;
};
G_LOCK_DEFINE (service_instance);
static gpointer service_instance = NULL;
G_DEFINE_TYPE (GSecretService, gsecret_service, G_TYPE_DBUS_PROXY);
static void
gsecret_session_free (gpointer data)
{
......@@ -67,6 +72,90 @@ gsecret_session_free (gpointer data)
g_free (session);
}
static void
gsecret_service_init (GSecretService *self)
{
self->pv = G_TYPE_INSTANCE_GET_PRIVATE (self, GSECRET_TYPE_SERVICE,
GSecretServicePrivate);
}
static void
gsecret_service_finalize (GObject *obj)
{
GSecretService *self = GSECRET_SERVICE (obj);
gsecret_session_free (self->pv->session);
G_OBJECT_CLASS (gsecret_service_parent_class)->finalize (obj);
}
static void
gsecret_service_class_init (GSecretServiceClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
object_class->finalize = gsecret_service_finalize;
g_type_class_add_private (klass, sizeof (GSecretServicePrivate));
}
static void
on_service_instance_gone (gpointer user_data,
GObject *where_the_object_was)
{
G_LOCK (service_instance);
g_assert (service_instance == where_the_object_was);
service_instance = NULL;
G_UNLOCK (service_instance);
}
GSecretService *
_gsecret_service_bare_instance (GDBusConnection *connection,
const gchar *bus_name)
{
GSecretService *service;
GError *error = NULL;
g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);
/* Alternate bus name is only used for testing */
if (bus_name == NULL)
bus_name = GSECRET_SERVICE_BUS_NAME;
service = g_initable_new (GSECRET_TYPE_SERVICE, NULL, &error,
"g-flags", G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
"g-interface-info", NULL, /* TODO: */
"g-name", bus_name,
"g-connection", connection,
"g-object-path", GSECRET_SERVICE_PATH,
"g-interface-name", GSECRET_SERVICE_INTERFACE,
NULL);
if (error != NULL) {
g_warning ("couldn't create GSecretService object: %s", error->message);
g_clear_error (&error);
return NULL;
}
g_assert (GSECRET_IS_SERVICE (service));
G_LOCK (service_instance);
if (service_instance == NULL) {
service_instance = service;
g_object_weak_ref (G_OBJECT (service), on_service_instance_gone, NULL);
} else {
g_object_unref (service);
service = g_object_ref (service_instance);
}
G_UNLOCK (service_instance);
return service;
}
#ifdef WITH_GCRYPT
static GVariant *
......@@ -330,14 +419,17 @@ gsecret_service_ensure_session (GSecretService *self,
}
const gchar *
gsecret_service_ensure_session_finish (GSecretService *self,
GAsyncResult *result,
GError **error)
_gsecret_service_ensure_session_finish (GSecretService *self,
GAsyncResult *result,
GCancellable **cancellable,
GError **error)
{
GSecretSession *session;
OpenSessionClosure *closure;
g_return_val_if_fail (GSECRET_IS_SERVICE (self), NULL);
g_return_val_if_fail (error == NULL || *error == NULL, NULL);
g_return_val_if_fail (cancellable == NULL || *cancellable == NULL, NULL);
g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (self),
gsecret_service_ensure_session), NULL);
......@@ -345,12 +437,25 @@ gsecret_service_ensure_session_finish (GSecretService *self,
if (g_simple_async_result_propagate_error (G_SIMPLE_ASYNC_RESULT (result), error))
return NULL;
if (cancellable) {
closure = g_simple_async_result_get_op_res_gpointer (G_SIMPLE_ASYNC_RESULT (result));
*cancellable = closure->cancellable ? g_object_ref (closure->cancellable) : NULL;
}
/* The session we have should never change once created */
session = g_atomic_pointer_get (&self->pv->session);
g_assert (session != NULL);
return session->path;
}
const gchar *
gsecret_service_ensure_session_finish (GSecretService *self,
GAsyncResult *result,
GError **error)
{
return _gsecret_service_ensure_session_finish (self, result, NULL, error);
}
const gchar *
gsecret_service_ensure_session_sync (GSecretService *self,
GCancellable *cancellable,
......
......@@ -13,9 +13,24 @@
#include "config.h"
#include "gsecret-private.h"
#include "gsecret-types.h"
#include <string.h>
GQuark
gsecret_error_get_quark (void)
{
static volatile gsize initialized = 0;
static GQuark quark = 0;
if (g_once_init_enter (&initialized)) {
quark = g_quark_from_static_string ("gsecret-error");
g_once_init_leave (&initialized, 1);
}
return quark;
}
gchar *
_gsecret_util_parent_path (const gchar *path)
{
......
......@@ -2,6 +2,7 @@ include $(top_srcdir)/Makefile.decl
INCLUDES = \
-I$(top_srcdir)/library \
-DSRCDIR="\"@abs_srcdir@\"" \
$(NULL)
LDADD = \
......@@ -10,7 +11,7 @@ LDADD = \
$(NULL)
TEST_PROGS = \
test-initial \
test-session \
$(NULL)
check_PROGRAMS = \
......
#!/usr/bin/env python
import mock
service = mock.SecretService()
service.listen()
\ No newline at end of file
This diff is collapsed.
# WARNING: This is for use in mock objects during testing, and NOT
# cryptographically secure or performant.
#
# Copyright 2011 Stef Walter
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; either version 2 of the licence or (at
# your option) any later version.
#
# See the included COPYING file for more information.
#
#
# Some utility functions from tlslite which is public domain
# Written by Trevor Perrin <trevp at trevp.net>
# http://trevp.net/tlslite/
#
import math
import random
PRIME = '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xC9\x0F\xDA\xA2\x21\x68\xC2\x34\xC4' \
'\xC6\x62\x8B\x80\xDC\x1C\xD1\x29\x02\x4E\x08\x8A\x67\xCC\x74\x02\x0B\xBE' \
'\xA6\x3B\x13\x9B\x22\x51\x4A\x08\x79\x8E\x34\x04\xDD\xEF\x95\x19\xB3\xCD' \
'\x3A\x43\x1B\x30\x2B\x0A\x6D\xF2\x5F\x14\x37\x4F\xE1\x35\x6D\x6D\x51\xC2' \
'\x45\xE4\x85\xB5\x76\x62\x5E\x7E\xC6\xF4\x4C\x42\xE9\xA6\x37\xED\x6B\x0B' \
'\xFF\x5C\xB6\xF4\x06\xB7\xED\xEE\x38\x6B\xFB\x5A\x89\x9F\xA5\xAE\x9F\x24' \
'\x11\x7C\x4B\x1F\xE6\x49\x28\x66\x51\xEC\xE6\x53\x81\xFF\xFF\xFF\xFF\xFF' \
'\xFF\xFF\xFF'
def num_bits(number):
if number == 0:
return 0
s = "%x" % number
return ((len(s)-1)*4) + \
{'0':0, '1':1, '2':2, '3':2,
'4':3, '5':3, '6':3, '7':3,
'8':4, '9':4, 'a':4, 'b':4,
'c':4, 'd':4, 'e':4, 'f':4,
}[s[0]]
def num_bytes(number):
if number == 0:
return 0
bits = num_bits(number)
return int(math.ceil(bits / 8.0))
def bytes_to_number(data):
number = 0L
multiplier = 1L
for count in range(len(data) - 1, -1, -1):
number += multiplier * ord(data[count])
multiplier *= 256
return number
def number_to_bytes(number):
n_data = num_bytes(number)
data = ['' for i in range(0, n_data)]
for count in range(n_data - 1, -1, -1):
data[count] = chr(number % 256)
number >>= 8
return "".join(data)
def generate_pair():
prime = bytes_to_number (PRIME)
base = 2
bits = num_bits(prime)
privat = 0
while privat == 0:
privat = random.getrandbits(bits - 1)
publi = pow(base, privat, prime)
return (privat, publi)
def derive_key(privat, peer):
prime = bytes_to_number (PRIME)
key = pow(peer, privat, prime)
return number_to_bytes(key)
# Upstream Author: Zooko O'Whielacronx <zooko@zooko.com>
#
# Copyright:
#
# You may use this package under the GNU General Public License, version
# 2 or, at your option, any later version. You may use this package
# under the Transitive Grace Period Public Licence, version 1.0 or, at
# your option, any later version. (You may choose to use this package
# under the terms of either licence, at your option.) See the file
# COPYING.GPL for the terms of the GNU General Public License, version 2.
# See the file COPYING.TGPPL.html for the terms of the Transitive Grace
# Period Public Licence, version 1.0.
#
# The following licensing text applies to a subset of the Crypto++ source code
# which is included in the pycryptopp source tree under the "embeddedcryptopp"
# subdirectory. That embedded subset of the Crypto++ source code is not used
# when pycryptopp is built for Debian -- instead the --disable-embedded-cryptopp
# option to "setup.py build" is used to for pycryptopp to build against the
# system libcryptopp.
import hashlib, hmac
import math
from binascii import a2b_hex, b2a_hex
class HKDF(object):
def __init__(self, ikm, L, salt=None, info="", digestmod = None):
self.ikm = ikm
self.keylen = L
if digestmod is None:
digestmod = hashlib.sha256
if callable(digestmod):
self.digest_cons = digestmod
else:
self.digest_cons = lambda d='':digestmod.new(d)
self.hashlen = len(self.digest_cons().digest())
if salt is None:
self.salt = chr(0)*(self.hashlen)
else:
self.salt = salt
self.info = info
#extract PRK
def extract(self):
h = hmac.new(self.salt, self.ikm, self.digest_cons)
self.prk = h.digest()
return self.prk
#expand PRK
def expand(self):
N = math.ceil(float(self.keylen)/self.hashlen)
T = ""
temp = ""
i=0x01
'''while len(T)<2*self.keylen :
msg = temp
msg += self.info
msg += b2a_hex(chr(i))
h = hmac.new(self.prk, a2b_hex(msg), self.digest_cons)
temp = b2a_hex(h.digest())
i += 1
T += temp
'''
while len(T)<self.keylen :
msg = temp
msg += self.info
msg += chr(i)
h = hmac.new(self.prk, msg, self.digest_cons)
temp = h.digest()
i += 1
T += temp
self.okm = T[0:self.keylen]
return self.okm
def new(ikm, L, salt=None, info="", digestmod = None):
return HKDF(ikm, L,salt,info,digestmod)
def hkdf(ikm, length, salt=None, info=""):
hk = HKDF(ikm, length ,salt,info)
computedprk = hk.extract()
return hk.expand()
\ No newline at end of file
#!/usr/bin/env python
#
# Copyright 2011 Stef Walter
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; either version 2 of the licence or (at
# your option) any later version.
#
# See the included COPYING file for more information.
#
import os
import sys
import getopt
import unittest
import aes
import dh
import hkdf
import dbus
import dbus.service
import dbus.glib
import gobject
bus_name = 'org.freedesktop.Secret.MockService'
class NotSupported(dbus.exceptions.DBusException):
def __init__(self, msg):
dbus.exceptions.DBusException.__init__(self, msg, name="org.freedesktop.DBus.Error.NotSupported")
......@@ -20,52 +37,90 @@ def next_identifier():
unique_identifier += 1
return unique_identifier
class PlainAlgorithm():
def negotiate(self, service, sender, param):
session = SecretSession(service, sender, None)
return (dbus.String("", variant_level=1), session)
class AesAlgorithm():
def negotiate(self, service, sender, param):
publi, privat = dh.generate_pair()
peer = dh.bytes_to_number(param)
ikm = dh.derive_key(privat, peer)
key = hkdf.hkdf(ikm, 16)
session = SecretSession(service, sender, key)
return (dbus.ByteArray(dh.number_to_bytes(publi), variant_level=1), session)
class SecretSession(dbus.service.Object):
def __init__(self, service, key):
global unique_identifier
def __init__(self, service, sender, key):
self.sender = sender
self.service = service
self.key = key
self.path = "/org/freedesktop/secrets/sessions/%d" % next_identifier()
dbus.service.Object.__init__(self, service.bus_name, self.path)
service.add_session(self)
@dbus.service.method('org.freedesktop.Secret.Session')
def Close(self):
self.remove_from_connection()
self.service.remove_session(self)
class SecretService(dbus.service.Object):
def __init__(self, name):
self.bus_name = dbus.service.BusName(name, bus = dbus.SessionBus())
algorithms = {
'plain': PlainAlgorithm(),
"dh-ietf1024-sha256-aes128-cbc-pkcs7": AesAlgorithm(),
}
def __init__(self, name=bus_name):
bus = bus = dbus.SessionBus()
self.bus_name = dbus.service.BusName(name)
dbus.service.Object.__init__(self, self.bus_name, '/org/freedesktop/secrets')
self.sessions = { }
def on_name_owner_changed(owned, old_owner, new_owner):
if not new_owner:
for session in list(self.sessions.get(old_owner, [])):
session.Close()
bus.add_signal_receiver(on_name_owner_changed,
'NameOwnerChanged',
'org.freedesktop.DBus')
def listen(self):
loop = gobject.MainLoop()
loop.run()
@dbus.service.method('org.freedesktop.Secret.Service')
def OpenSession(self, algorithm, input):
assert type(algorithm) == dbus.String
# assert type(input) == dbus.ByteArray
def add_session(self, session):
if session.sender not in self.sessions:
self.sessions[session.sender] = []
self.sessions[session.sender].append(session)
if algorithm == "plain":
session = SecretSession(self, None)
self.sessions[session.path] = session
return (dbus.String("", variant_level=1), session)
def remove_session(self, session):
self.sessions[session.sender].remove(session)
@dbus.service.method('org.freedesktop.Secret.Service', byte_arrays=True, sender_keyword='sender')
def OpenSession(self, algorithm, param, sender=None):
assert type(algorithm) == dbus.String
assert type(param) == dbus.ByteArray
elif algorithm == "dh-ietf1024-sha256-aes128-cbc-pkcs7":
if algorithm not in self.algorithms:
raise NotSupported("algorithm %s is not supported" % algorithm)
else:
assert False, "algorithm %s not recognized" % algorithm
return self.algorithms[algorithm].negotiate(self, sender, param)
if __name__ == '__main__':
def parse_options(args):
global bus_name
try:
opts, args = getopt.getopt(sys.argv[1:], "name", ["name="])
opts, args = getopt.getopt(args, "name", ["name="])
except getopt.GetoptError, err:
print str(err)
sys.exit(2)
name = 'org.freedesktop.Secret.MockService'
for o, a in opts:
if o in ("--name"):
name = a
bus_name = a
else:
assert False, "unhandled option"
return args
myservice = SecretService(name)
myservice.listen()
\ No newline at end of file
parse_options(sys.argv[1:])
\ No newline at end of file
......@@ -15,25 +15,75 @@
#include "gsecret-item.h"
#include "gsecret-service.h"
#include "gsecret-private.h"
#include <glib.h>
#include <errno.h>
#include <stdlib.h>
static gchar *MOCK_NAME = "org.mock.Service";
typedef struct {
GPid pid;
GDBusConnection *connection;
GSecretService *service;
} Test;
static void
setup_normal (Test *test,
gconstpointer unused)