ADD_DEFINITIONS("-DAPI_VERSION=\"$(API_VERSION)\"")
ADD_SUBDIRECTORY(server)
+ADD_SUBDIRECTORY(setting)
ADD_SUBDIRECTORY(client)
ADD_SUBDIRECTORY(pkgmgr_plugin)
ADD_SUBDIRECTORY(test)
\ No newline at end of file
--- /dev/null
+# This file contains a list of people who've made non-trivial contribution
+# to the Privacy Setting project. People who commit code to the project are
+# encouraged to add their names here. Please keep the list sorted by first
+# names.
+
+Bartlomiej Grzelewski <b.grzelewski@samsung.com>
+Eduardo Iyoda <emi@cesar.org.br>
+Fabio Urquiza <flus@cesar.org.br>
+Gabriel Finch <gf@cesar.org.br>
+Jooseong Lee <jooseong.lee@samsung.com>
+Jungkon Kim <jungkon.kim@samsung.com>
+Kim Kidong <kd0228.kim@samsung.com>
+Kyoungyong Lee <k.y.lee@samsung.com>
+MyungJoo Ham <myungjoo.ham@samsung.com>
+Saulo Moraes <s.moraes@samsung.com>
+Seonil Kim <seonil47.kim@samsung.com>
+Yunjin Lee <yunjin-.lee@samsung.com>
EXTERN_API ac_instance *ahocorasick_init(void);
/**
- * @fn int ahocorasick_add_string(ac_instance *ac, const char *string, void *user_data)
+ * @fn int ahocorasick_add_string(ac_instance *ac, const char *string, void *user_data)
* @brief Add another string to the list for matching *
* @param[in] ac An instance returned from ahocorasick_init()
* @param[in] string The string to add
* @param[in] user_data User data to associate with any resulting matches
- * @return Count of total strings added
+ * @return Count of total strings added
* @callgraph
*/
EXTERN_API int ahocorasick_add_string(ac_instance *ac, const char *string, void *user_data);
/**
* @fn void ahocorasick_set_text(ac_instance *ac, const char *text, size_t textlen, int cont)
- * @brief Set the text to be scanned for matches
+ * @brief Set the text to be scanned for matches
* @param[in] ac An instance returned from ahocorasick_init()
* @param[in] text The text to be scanned
* @param[in] textlen The length of the text to be scanned, in bytes
* @fn ac_match *ahocorasick_find_next(ac_instance *ac)
* @brief Find the next match in the text
* @param[in] ac An instance returned from ahocorasick_init()
- * @return The next match in the text, or NULL. Matches are returned
- * in the order in which they end in the text, in alphanumeric order.
+ * @return The next match in the text, or NULL. Matches are returned
+ * in the order in which they end in the text, in alphanumeric order.
* @callgraph
*/
EXTERN_API ac_match *ahocorasick_find_next(ac_instance *ac);
/**
- * @fn oid ahocorasick_free(ac_instance *ac);
+ * @fn oid ahocorasick_free(ac_instance *ac);
* @brief Free an ahocorasick instance
* @param[in] ac An instance returned from ahocorasick_init()
* @callgraph
/**
Create a new node using the given rule id and text string
*/
-static ac_node *new_node(void *user_data, const char *text)
+static ac_node *new_node_strlen(void *user_data, const char *text, size_t textlen)
{
ac_node *node = (ac_node *)malloc(sizeof(ac_node));
memset(node, 0, sizeof(ac_node));
- node->branch = strdup(text);
+ if (textlen > 0) {
+ node->branch = (char *)malloc(textlen);
+ memcpy(node->branch, text, textlen);
+ node->brlen = (int)textlen;
+ }
node->user_data = user_data;
- node->is_match = TRUE;
+ node->checked = FALSE;
+ node->terminal = TRUE;
return node;
}
+static ac_node *new_node(void *user_data, const char *text)
+{
+ return new_node_strlen(user_data, text, strlen(text));
+}
+
/**
Append child (leaf) node to parent at position idx
*/
{
int nleaves = 2;
- int i;
ac_node **old_leaves = parent->leaves;
if (parent->leaves != NULL) {
while (parent->leaves[nleaves - 2] != NULL)
}
parent->leaves = (ac_node **)malloc(nleaves * sizeof(ac_node *));
if (parent->leaves != NULL) {
+ int i;
for (i = 0; i < nleaves - 1; i++) {
if (i < idx)
parent->leaves[i] = old_leaves[i];
/**
Compare string s1 with string s2
return value:
- 0 => s1 before s2
- -1 => s1 after s2
- other values => Number of initial letters in common
+ 0 => s1 before s2
+ -1 => s1 after s2
+ other values => Number of initial letters in common
+#ifdef CASE_INSENSITIVE
+ case conversion (tolower) should be done before calling compare()
+#endif
*/
-static int compare(const char *s1, const char *s2)
+static int compare(const char *s1, size_t s1len, const char *s2, size_t s2len)
{
int i;
- size_t commonlen, s2len;
-
- if (strlen(s1) == 0)
- return 0;
+ size_t commonlen;
- if (strlen(s2) == 0)
- return -1;
-
-#ifdef CASE_INSENSITIVE
- if (tolower(s1[0]) < tolower(s2[0]))
+ if (s1len == 0)
return 0;
- if (tolower(s2[0]) < tolower(s1[0]))
+ if (s2len == 0)
return -1;
-#else
if (s1[0] < s2[0])
return 0;
if (s2[0] < s1[0])
return -1;
-#endif
- commonlen = strlen(s1);
- if ((s2len = strlen(s2)) < commonlen)
+ commonlen = s1len;
+ if (s2len < commonlen)
commonlen = s2len;
for (i = 1; i < commonlen; i++) {
-#ifdef CASE_INSENSITIVE
- if (tolower(s1[i]) != tolower(s2[i]))
- return i;
-#else
if (s1[i] != s2[i])
return i;
-#endif
}
return commonlen;
}
{
ac_match *match = (ac_match *)malloc(sizeof(ac_match));
- if(match) {
+ if (match) {
match->user_data = user_data;
match->position = pos;
match->size = size;
static void add_sposn(ac_node *node, int offs)
{
int *old_sposns = node->sposns;
- int i;
/* do not add same position twice */
if (node->nsposns > 0 && node->sposns[0] == offs)
node->nsposns++;
node->sposns = (int *)malloc(node->nsposns * sizeof(int));
- if(node->sposns) {
+ if (node->sposns) {
node->sposns[0] = offs;
+ int i;
for (i = 1; i < node->nsposns; i++)
node->sposns[i] = old_sposns[i - 1];
}
{
int *old_sposns = node->sposns;
int nbad = 0;
- int i, j = 0;
+ int i;
for (i = 0; i < node->nsposns; i++) {
if (node->sposns[i] == -1)
} else {
node->sposns = (int *)malloc(node->nsposns * sizeof(int));
+ int j = 0;
for (i = 0; i < node->nsposns; i++) {
while (old_sposns[j] == -1)
j++;
*/
static int get_totlen(ac_node *node)
{
- size_t len = strlen(node->branch);
- while (node->stem != NULL) {
- node = node->stem;
- len += strlen(node->branch);
- }
- return (int)len;
+ int len = node->brlen;
+ if (node->stem != NULL)
+ len += get_totlen(node->stem);
+ return len;
+}
+
+#ifdef CASE_INSENSITIVE
+/**
+ convert string to all lower case. Result should be freed after use.
+*/
+static char *string_tolower(const char *string, size_t len)
+{
+ int i;
+ char *tl_string = (char *)malloc(len + 1);
+ if (!tl_string) return NULL;
+ for (i = 0; i < len; i++)
+ tl_string[i] = (char)tolower(string[i]);
+ tl_string[len] = 0;
+ return tl_string;
}
+#endif
void add_node(ac_instance *ac, const char *string, void *user_data)
{
- char *ptr = (char *)string;
+ char *ptr, *tmpptr;
+ size_t stlen = strlen(string);
ac_node *node = ac->root, *xnode;
- int finished = 0;
+ boolean finished = FALSE;
int res;
int i = 0;
+#ifdef CASE_INSENSITIVE
+ char *xstring = string_tolower(string, stlen);
+ if (xstring == NULL) return;
+ ptr = xstring;
+#else
+ ptr = (char *)string;
+#endif
+
while (!finished) {
+ boolean override_finished = FALSE;
if (node != NULL && node->leaves != NULL) {
/* starting with the root node, we look at each leaf in turn */
for (i = 0; (xnode = node->leaves[i]) != NULL; i++) {
* - if common is l.t branch, common part becomes node, and branch and node become children
* c) xnode->branch > text, insert node before xnode */
- res = compare(xnode->branch, ptr);
+ res = compare(xnode->branch, xnode->brlen, ptr, stlen);
if (res == 0)
/* xnode before new node */
} else {
ac_node *child1;
/* res letters were in common */
- if (res == strlen(xnode->branch)) {
+ node = xnode; // consider only this child node
+ if (res == node->brlen) {
/* all letters in common, so now we check the leaves */
- node = xnode;
ptr += res;
- if (strlen(ptr) == 0) {
+ stlen = strlen(ptr);
+ if (stlen == 0) {
/* duplicate string */
node->user_data = user_data;
- node->is_match = TRUE;
+ node->terminal = TRUE;
+#ifdef CASE_INSENSITIVE
+ free(xstring);
+#endif
return;
}
/* leave for() loop and continue in while (!finished) */
- i = 0;
+ if (node->leaves != NULL) {
+ // if it also has child leaves, override setting of finished
+ override_finished = TRUE;
+ } else i = 0; // otherwise add us as the first child
break;
}
/* the common part was l.t. all
* the common part becomes the new node
* we add both this node with all its children and the new node as children */
- child1 = new_node(xnode->user_data, (const char *)(xnode->branch + res));
+ child1 = new_node_strlen(xnode->user_data, (const char *)(xnode->branch + res), xnode->brlen - res);
child1->leaves = xnode->leaves;
child1->stem = xnode;
+ child1->terminal = xnode->terminal;
if (child1->leaves != NULL) {
for (i = 0; (node = child1->leaves[i]) != NULL; i++) {
/* adjust stems for each of these */
}
}
/* remove xnodes leaves and shorten its text */
- memset(xnode->branch + res, 0, 1);
+ tmpptr = (char *)malloc(res);
+ memcpy(tmpptr, xnode->branch, res);
+ free(xnode->branch);
+ xnode->branch = tmpptr;
+ xnode->brlen = res;
- if (strlen(ptr) > res) {
+ if (stlen > res) {
ac_node *child2;
/* remainder of new string is added as child2 */
- xnode->is_match = FALSE;
+ xnode->terminal = FALSE;
xnode->leaves = (ac_node **)malloc(3 * sizeof(ac_node *));
if (xnode->leaves != NULL) {
- child2 = new_node(user_data, (const char *)(ptr + res));
- ac->added++;
- child2->stem = xnode;
-
- res = compare(child1->branch, child2->branch);
- if (res == 0) {
- /* child1 before child2 */
- xnode->leaves[0] = child1;
- xnode->leaves[1] = child2;
- } else {
- /* child1 before child2 */
- xnode->leaves[0] = child2;
- xnode->leaves[1] = child1;
- }
- xnode->leaves[2] = NULL;
+ child2 = new_node(user_data, (const char *)(ptr + res));
+ ac->added++;
+ child2->stem = xnode;
+
+ res = compare(child1->branch, child1->brlen, child2->branch, child2->brlen);
+ if (res == 0) {
+ /* child1 before child2 */
+ xnode->leaves[0] = child1;
+ xnode->leaves[1] = child2;
+ } else {
+ /* child1 before child2 */
+ xnode->leaves[0] = child2;
+ xnode->leaves[1] = child1;
+ }
+ xnode->leaves[2] = NULL;
}
} else {
/* the common part consumed all of new string, so we only have 1 child to add */
+ xnode->terminal = TRUE;
xnode->leaves = (ac_node **)malloc(2 * sizeof(ac_node *));
if (xnode->leaves != NULL) {
- xnode->user_data = user_data;
- xnode->leaves[0] = child1;
- xnode->leaves[1] = NULL;
+ xnode->user_data = user_data;
+ xnode->leaves[0] = child1;
+ xnode->leaves[1] = NULL;
}
}
}
+#ifdef CASE_INSENSITIVE
+ free(xstring);
+#endif
return;
}
}
- finished = 1;
+ if (!override_finished) finished = TRUE;
}
/* we checked all children and none were after ptr */
if (ac->root == NULL) {
/* new root - make a root node and add us as a leaf */
node = ac->root = new_node(NULL, "");
- ac->root->is_match = FALSE;
+ ac->root->terminal = FALSE;
}
add_child(node, i, xnode);
+#ifdef CASE_INSENSITIVE
+ free(xstring);
+#endif
}
/**
* @callgraph
*/
-ac_match *parse_char(char ch, int offs, ac_node *node)
+static ac_match *parse_char_with_case(unsigned char ch, int offs, ac_node *node)
{
ac_match *acm = NULL;
ac_node *xnode;
- size_t brlen;
- int child_sposns = 0;
- int i, j;
+ int i;
- if (node->checked)
- return NULL;
+ if (!node || node->checked) return NULL;
- brlen = strlen(node->branch);
- if (brlen > 0) {
-#ifdef CASE_INSENSITIVE
- if (node->stem->stem == NULL && tolower(node->branch[0]) == tolower(ch)) {
- /* leaf of root node, and first char matched, start a new sposn */
- add_sposn(node, offs);
+ if (node->leaves != NULL && (node->brlen == 0 || node->child_sposns != 0)) {
+ /* starting from the root, we look at each unchecked child in turn and check (recursively) for matches
+ * (skip if there are no child_sposns, to avoid parsing the whole tree) */
+ for (i = 0; (xnode = node->leaves[i]) != NULL && !xnode->checked; i++) {
+ if (node->brlen == 0 || xnode->nsposns > 0 || xnode->child_sposns > 0) {
+ acm = parse_char_with_case(ch, offs, xnode);
+ if (acm != NULL)
+ return acm;
+ }
}
-#else
- if (node->stem->stem == NULL && node->branch[0] == ch) {
+ }
+
+ /* after checking the child nodes, we look at the node itself */
+
+ if (node->brlen > 0) {
+ /* the cast is just to prevent SVACE warnings, as long as both types are the same it does not matter */
+ if (node->stem->stem == NULL && (unsigned char)node->branch[0] == ch) {
/* leaf of root node, and first char matched, start a new sposn */
add_sposn(node, offs);
}
-#endif
+
if (node->nsposns > 0) {
+ int child_sposns = 0;
/* first check the ongoing matches in sposns */
for (i = 0; i < node->nsposns; i++) {
- if (node->sposns[i] > offs)
- continue;
-
-#ifdef CASE_INSENSITIVE
- if (tolower(node->branch[offs - node->sposns[i]]) != tolower(ch)) {
- /* mark for removal */
- node->sposns[i] = -1;
- } else {
-#else
- if (node->branch[offs - node->sposns[i]] != ch) {
- /* mark for removal */
+ int sposn = node->sposns[i];
+ /* the cast is just to prevent SVACE warnings, as long as both types are the same it does not matter */
+ if ((unsigned char)node->branch[offs - sposn] != ch) {
+ /* mismatch, mark for removal */
node->sposns[i] = -1;
- } else {
-#endif
- /* continuing match */
- if (offs - node->sposns[i] == brlen - 1) {
- /* the entirety of this branch was matched */
- if (node->leaves == NULL || node->is_match) {
- /* we got a match ! */
- int totlen = get_totlen(node);
- acm = create_match(node->user_data, node->sposns[i] - totlen + brlen, totlen);
+ } else if (offs - sposn == node->brlen - 1) {
+ /* the entirety of this branch was matched */
+ if (node->terminal) {
+ /* we got a match ! */
+ int totlen = get_totlen(node);
+ if (acm == NULL) {
+ // since the values of node->sposns[] are unique, acm should always be NULL
+ // the check is added to prevent SVACE warnings
+ acm = create_match(node->user_data, sposn - totlen + node->brlen, totlen);
}
- if (node->leaves != NULL) {
- /* otherwise place possible matches at next char for all children */
- for (j = 0; (xnode = node->leaves[j]) != NULL; j++) {
- add_sposn(xnode, offs + 1);
- child_sposns++;
- }
+ }
+ if (node->leaves != NULL) {
+ /* place possible matches at next char for all children */
+ int j;
+ for (j = 0; (xnode = node->leaves[j]) != NULL; j++) {
+ add_sposn(xnode, offs + 1);
+ child_sposns++;
}
- /* mark for removal */
- node->sposns[i] = -1;
+ /* increase child sposn count for node and all ancestors */
+ ancestors_increment_sposns(node, child_sposns);
}
+ /* mark for removal */
+ node->sposns[i] = -1;
}
}
- }
-
- /* after checking all sposns we clean up bad matches */
- clean_bad_sposns(node);
- }
-
- if (acm == NULL) {
- if (node->leaves != NULL && (brlen == 0 || node->child_sposns != 0)) {
- /* starting from the root, we look at each leaf in turn and check for matches
- * (skip if there are no child_sposns, to avoid parsing the whole tree) */
- for (i = 0; (xnode = node->leaves[i]) != NULL; i++) {
- acm = parse_char(ch, offs, xnode);
- if (acm != NULL)
- return acm;
- }
+ /* after checking all sposns we clean up bad matches */
+ clean_bad_sposns(node);
}
- }
- /* increase child sposn count for node and all ancestors */
- if (child_sposns != 0)
- ancestors_increment_sposns(node, child_sposns);
+ /* mark this node as checked for this position */
+ node->checked = TRUE;
+ }
- /* mark this node as checked for this position */
- node->checked = 1;
return acm;
}
+/**
+ * @callgraph
+ */
+ac_match *parse_char(unsigned char ch, int offs, ac_node *node)
+{
+#ifdef CASE_INSENSITIVE
+ return parse_char_with_case(tolower(ch), offs, node);
+#else
+ return parse_char_with_case(ch, offs, node);
+#endif
+}
+
void reset_checks(ac_node *node)
{
- int i;
- node->checked = 0;
+ if (!node) return;
+ node->checked = FALSE;
if (node->leaves != NULL) {
ac_node *xnode;
+ int i;
for (i = 0; (xnode = node->leaves[i]) != NULL; i++)
reset_checks(xnode);
}
void tree_free(ac_node *node)
{
- int i;
if (node->branch != NULL)
free(node->branch);
if (node->leaves != NULL) {
ac_node *xnode;
+ int i;
for (i = 0; (xnode = node->leaves[i]) != NULL; i++)
tree_free(xnode);
free(node);
}
-void dump_tree(ac_node *node)
+void dump_tree(ac_node *node, FILE *stream)
{
int i;
ac_node *xnode;
- printf("%s (%p)", node->branch, node->user_data);
+ int otabbing, xtabbing;
+ static int tabbing;
+
+ if (!node) return;
+
+ if (node->branch == NULL || node->stem->brlen == 0)
+ tabbing = 0;
+
+ for (i = 0; i < tabbing; i++)
+ fprintf(stream, " ");
+
+ otabbing = tabbing;
+
+ if (node->brlen > 0) {
+ char *word = malloc(node->brlen + 1);
+ memcpy(word, node->branch, node->brlen);
+ memset(word + node->brlen, 0, 1);
+ fprintf(stream, "%s (%p)", word, node->user_data);
+ free(word);
+ tabbing += node->brlen + 10;
+ if (node->terminal) fprintf(stream, " |");
+ }
if (node->leaves == NULL) {
- printf("\n");
+ fprintf(stream, "\n");
return;
}
- printf(" ");
+ fprintf(stream, "->\n");
+
+ xtabbing = tabbing;
+
+ for (i = 0; (xnode = node->leaves[i]) != NULL; i++) {
+ dump_tree(xnode, stream);
+ tabbing = xtabbing;
+ }
- for (i = 0; (xnode = node->leaves[i]) != NULL; i++)
- dump_tree(xnode);
+ tabbing = otabbing;
}
void clear_sposns(ac_node *node)
{
- int i;
-
if (node == NULL)
return;
if (node->leaves != NULL) {
ac_node *xnode;
+ int i;
for (i = 0; (xnode = node->leaves[i]) != NULL; i++)
clear_sposns(xnode);
}
#ifndef _AHOCORASICK_NODE_H_
#define _AHOCORASICK_NODE_H_
+#include <stdio.h>
+
#include "types.h"
#ifdef __cplusplus
void add_node(ac_instance *ac, const char *string, void *user_data);
/**
- * @fn ac_match *parse_char(char ch, int offs, ac_node *node)
+ * @fn ac_match *parse_char(unsigned char ch, int offs, ac_node *node)
* @brief Parse char at offs in the source text, using the tree rooted at node
* @param[in] ch The character at offs in the source text
* @param[in] offs The offset of the character in the source text
* @return The next match at position offs, or NULL if no more matches.
* @callgraph
*/
-ac_match *parse_char(char ch, int offs, ac_node *node);
+ac_match *parse_char(unsigned char ch, int offs, ac_node *node);
/**
* @fn void clear_sposns(ac_node *node)
/**
* @fn void reset_checks(ac_node *node)
* @brief Each node is marked checked as the tree is traversed. When there are no more matches
- * at a position, this function is called to clear the checks.
+ * at a position, this function is called to clear the checks.
* @param[in] node the root of the tree to be traversed.
* @callgraph
*/
* @fn void dump_tree(ac_node *node)
* @brief This is a test function which prints out the current tree of string fragments.
* @param[in] node The root of the tree to be traversed.
+ * @param[in] stream The stream to print the output to, e.g. stdout, stderr.
* @callgraph
*/
-void dump_tree(ac_node *node);
+void dump_tree(ac_node *node, FILE *stream);
#ifdef __cplusplus
}
#endif
typedef struct _ac_node ac_node;
-typedef int boolean;
+typedef unsigned char boolean;
#ifndef TRUE
#define TRUE 1
struct _ac_node {
void *user_data; ///< the user_data which was added with the string
- boolean is_match; ///< is this node the terminal of some match
+ boolean terminal; ///< is this node the terminal of some match
ac_node *stem; ///< node which this is a leaf of (or NULL)
- char *branch; ///< differential text following stem
+ char *branch; ///< differential text following stem (not NUL terminated)
+ int brlen; ///< length of *branch* (bytes)
ac_node **leaves; ///< various bits of text which can be appended to stem | branch
int *sposns; ///< used during matching - possible start positions of this branch
int nsposns; ///< number of sposns
int child_sposns; ///< number of sposns of descendents
- int checked; ///< if the node has been checked for the current position
+ boolean checked; ///< if the node + children has been checked for the current position
};
typedef struct {
int offs; ///< how far we have parsed
ac_match *match; ///< latest match
ac_node *root; ///< pointer to the string matching tree
- int added; ///< how many nodes added
+ int added; ///< how many strings added
} ac_instance;
#ifdef __cplusplus
SET(INCLUDEDIR ${INCLUDE_INSTALL_DIR})
INCLUDE(FindPkgConfig)
-pkg_check_modules(privacy-guard-client REQUIRED dlog sqlite3 dbus-1 dbus-glib-1 db-util pkgmgr-info libtzplatform-config libpcre)
+pkg_check_modules(privacy-guard-client REQUIRED dlog libtzplatform-config libpcre)
FOREACH(flag ${pkgs_CFLAGS})
SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
## for libprivacy-guard-client
INCLUDE_DIRECTORIES(${pkgs_INCLUDE_DIRS} ${client_include_dir} ${common_include_dir} ${extern_include_dir})
SET(PRIVACY_GUARD_CLIENT_SOURCES
+ ${ahocorasick_dir}/ahocorasick.c
+ ${ahocorasick_dir}/node.c
+ ${common_src_dir}/DlpUtils.cpp
+ ${common_src_dir}/privacy_guard_utils.c
+ ${common_src_dir}/SocketClient.cpp
${common_src_dir}/SocketConnection.cpp
${common_src_dir}/SocketStream.cpp
- ${common_src_dir}/PrivacyIdInfo.cpp
- ${common_src_dir}/DlpUtils.cpp
${common_src_dir}/Utils.cpp
- ${common_src_dir}/privacy_guard_utils.c
- ${client_src_dir}/SocketClient.cpp
- ${client_src_dir}/PrivacyChecker.cpp
- ${client_src_dir}/PrivacyGuardClient.cpp
- ${client_src_dir}/privacy_guard_client.cpp
- ${client_src_dir}/privacy_guard_dlp.cpp
+ ${client_src_dir}/DlpLogsManager.cpp
${client_src_dir}/DlpPacketParser.cpp
${client_src_dir}/DlpRulesManager.cpp
- ${client_src_dir}/DlpLogsManager.cpp
- ${ahocorasick_dir}/ahocorasick.c
- ${ahocorasick_dir}/node.c
+ ${client_src_dir}/PrivacyGuardDlp.cpp
+ ${client_src_dir}/privacy_guard_dlp.cpp
)
SET(PRIVACY_GUARD_CLIENT_HEADERS
- ${client_include_dir}/PrivacyChecker.h
- ${client_include_dir}/PrivacyGuardClient.h
- ${client_include_dir}/DlpPacketParserResult.h
- ${client_include_dir}/DlpPacketParser.h
- ${client_include_dir}/privacy_guard_client_internal.h
- ${client_include_dir}/DlpRulesManager.h
- ${client_include_dir}/DlpLogsManager.h
${ahocorasick_dir}/ahocorasick.h
${ahocorasick_dir}/node.h
${ahocorasick_dir}/types.h
+ ${common_include_dir}/DlpPacketParserResult.h
+ ${common_include_dir}/DlpUtils.h
+ ${common_include_dir}/privacy_guard_utils.h
+ ${common_include_dir}/SocketClient.h
+ ${common_include_dir}/SocketConnection.h
+ ${common_include_dir}/SocketStream.h
+ ${common_include_dir}/Utils.h
+ ${client_include_dir}/DlpLogsManager.h
+ ${client_include_dir}/DlpPacketParser.h
+ ${client_include_dir}/DlpRulesManager.h
+ ${client_include_dir}/PrivacyGuardDlp.h
)
SET(PRIVACY_GUARD_EXTERN_HEADERS
- ${extern_include_dir}/privacy_guard_client.h
- ${extern_include_dir}/privacy_guard_dlp.h
${extern_include_dir}/privacy_guard_client_types.h
+ ${extern_include_dir}/privacy_guard_dlp.h
)
SET(PRIVACY_GUARD_CLIENT_LDFLAGS " -module -avoid-version ")
INSTALL(TARGETS privacy-guard-client DESTINATION ${LIB_INSTALL_DIR} COMPONENT RuntimeLibraries)
INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/privacy-guard-client.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig)
INSTALL(FILES ${PRIVACY_GUARD_CLIENT_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard/client)
-INSTALL(FILES ${PRIVACY_GUARD_EXTERN_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard)
+INSTALL(FILES ${PRIVACY_GUARD_EXTERN_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard)
\ No newline at end of file
#include <list>
#include "DlpPacketParser.h"
#include "DlpPacketParserResult.h"
-#include "PrivacyGuardClient.h"
#include "PrivacyGuardTypes.h"
typedef struct _leak_log_queue_entry_s {
current_rules_list rlist;
} leak_log_queue_entry_s;
+class PrivacyGuardDlp;
class EXTERN_API DlpLogsManager
{
static std::mutex m_singletonMutex;
static DlpLogsManager *m_pInstance;
std::list<leak_log_queue_entry_s> m_logQueue;
- PrivacyGuardClient *m_privacyGuardClient;
+ PrivacyGuardDlp *m_privacyGuardDlp;
std::mutex m_logQueueMutex;
std::mutex m_leakLogSendMutex;
*
* @param[in] entry The leaked information to be verified
*
- * @return The overall action to be taken given the individual results,
- * either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
- * or PRIV_GUARD_DLP_RESULT_DENY.
+ * @return The overall action to be taken given the individual results,
+ * either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
+ * or PRIV_GUARD_DLP_RESULT_DENY.
*/
PgDlpResult ParseAndLogLeakNow(leak_log_queue_entry_s &entry);
* @param[in] len The length of the data packet in bytes
* @param[in] rules The rules to use when parsing the data
*
- * @return The overall action to be taken given the individual results,
- * either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
- * or PRIV_GUARD_DLP_RESULT_DENY.
+ * @return The overall action to be taken given the individual results,
+ * either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
+ * or PRIV_GUARD_DLP_RESULT_DENY.
*/
PgDlpResult ParseAndLogLeak(const char *hostname, char *mem, size_t len, const current_rules_list &rules);
* @brief Set the rules for the packet parser
*
* @param[in] rules Pointer to a std::list of current_rules_s.
- * The rules are not copied so they must remain valid while parsePacket() or sanitize() is called.
+ * The rules are not copied so they must remain valid while parsePacket() or sanitize() is called.
*
* @return count of rules in the list
*/
/**
* @fn PgDlpResult parsePacket(char * const pdata, size_t length, DlpPacketParserResultList &rl)
* @brief Parse a packet of data and return a std::list of DlpPacketParserResult.
- * Before calling this it is necessary to set rules (once) with setRules().
- * After calling this you may call sanitize() to sanitize the packet.
+ * Before calling this it is necessary to set rules (once) with setRules().
+ * After calling this you may call sanitize() to sanitize the packet.
*
- * @param[in] pdata pointer to the packet data to be parsed. If sanitization is to be performed,
- * the data must not be freed until after sanitize() is called.
- * @param[in] length byte length of the packet data to be parsed
- * @param[out] rl std::list of DlpPacketParserResult. List may be empty.
+ * @param[in] pdata pointer to the packet data to be parsed. If sanitization is to be performed,
+ * the data must not be freed until after sanitize() is called.
+ * @param[in] length byte length of the packet data to be parsed
+ * @param[out] rl std::list of DlpPacketParserResult. List may be empty.
*
- * @return The overall action to be taken given the individual results,
- * either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
- * or PRIV_GUARD_DLP_RESULT_DENY.
+ * @return The overall action to be taken given the individual results,
+ * either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
+ * or PRIV_GUARD_DLP_RESULT_DENY.
*/
PgDlpResult parsePacket(char * const pdata, size_t length, DlpPacketParserResultList &rl);
* @brief Get the overall action given a list of DlpPacketParserResult.
*
* @param[in] pdata pointer to the packet data to be parsed. If sanitization is to be performed,
- * the data must not be freed until after sanitize() is called.
+ * the data must not be freed until after sanitize() is called.
* @param[in] length byte length of the packet data to be parsed
* @param[in] rl std::list of DlpPacketParserResult. List may be empty.
*
/**
* @file DlpRulesManager.h
- * @brief Manages the packet parsing rules for a client
+ * @brief Manages the packet parsing rules for dlp library
*/
#ifndef _DLPRULESMANAGER_H_
#include <string>
#include <mutex>
#include <list>
-#include "PrivacyGuardClient.h"
#include "PrivacyGuardTypes.h"
+class PrivacyGuardDlp;
+
class EXTERN_API DlpRulesManager
{
private:
static std::mutex m_singletonMutex;
static DlpRulesManager *m_pInstance;
std::list<current_rules_s> m_currentRules;
- PrivacyGuardClient *m_privacyGuardClient;
+ PrivacyGuardDlp *m_privacyGuardDlp;
std::mutex m_rulesMutex;
DlpRulesManager();
+++ /dev/null
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @file PrivacyChecker.h
- */
-
-#ifndef _PRIVACY_CHECKER_H_
-#define _PRIVACY_CHECKER_H_
-
-#include <string>
-#include <mutex>
-#include <list>
-#include <vector>
-#include <memory>
-#include <map>
-#include <dbus/dbus.h>
-#include <glib.h>
-#include "PrivacyGuardTypes.h"
-
-struct sqlite3;
-
-class EXTERN_API PrivacyChecker
-{
-private:
- static std::map < std::string, bool > m_privacyCache;
- static std::map < std::string, std::map < std::string, bool > > m_privacyInfoCache;
- static std::map < std::string, int > m_monitorPolicyCache;
- static std::string m_pkgId;
- static bool m_isInitialized;
- static bool m_isMonitorEnable;
- static std::mutex m_cacheMutex;
- static std::mutex m_dbusMutex;
- static std::mutex m_initializeMutex;
- static DBusConnection* m_pDBusConnection;
- static GMainLoop* m_pLoop;
- static GMainContext* m_pHandlerGMainContext;
- static pthread_t m_signalThread;
-
-private:
- static int initializeDbus(void);
- static int finalizeDbus(void);
- static int updateCache(const std::string pkgId, std::string privacyId, std::map<std::string, bool> &pkgCacheMap);
- static int updateCache(const std::string pkgId, std::map<std::string, bool> &pkgCacheMap);
- static void printCache(void);
- static void* runSignalListenerThread(void *pData);
- static int getCurrentPkgId(std::string &pkgId);
- static int check(const std::string privacyId, std::map<std::string, bool> &privacyMap);
-
-public:
- // for Checking in App Process
- static int initialize(void);
- static int check(const std::string pkgId, const std::string privacyId);
- static int checkWithDeviceCap(const std::string pkgId, const std::string deviceCap);
-
- // for Checking in Server Process
- static int initializeGMain(void);
- static int check(const std::string privacyId);
- static void checkMonitorByPrivilege(const std::string privilegeId);
- static int checkWithDeviceCap(const std::string deviceCap);
- static void printMonitorPolicyCache(void);
- static int initMonitorPolicyCache(void);
- static int getMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, int &monitorPolicy);
-
- // common
- static int finalize(void);
- static DBusHandlerResult handleNotification(DBusConnection *connection, DBusMessage *message, void *user_data);
-};
-
-#endif // _PRIVACY_CHECKER_H_
--- /dev/null
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file PrivacyGuardDlp.h
+ */
+
+#ifndef _PRIVACYGUARDDLP_H_
+#define _PRIVACYGUARDDLP_H_
+
+#include <string>
+#include <mutex>
+#include <list>
+#include "PrivacyGuardTypes.h"
+
+class EXTERN_API PrivacyGuardDlp
+{
+private:
+ static PrivacyGuardDlp* m_pInstance;
+ static const std::string INTERFACE_NAME;
+
+ static std::mutex m_singletonMutex;
+
+ PrivacyGuardDlp();
+ ~PrivacyGuardDlp();
+
+ //void loadApplicationInfo();
+
+public:
+ static PrivacyGuardDlp* getInstance();
+
+ /**
+ * @brief add a list of leak logs to the database
+ *
+ * @param[in] userId The ID of the user running the application
+ * @param[in] pId The process ID of the application
+ * @param[in] destination The host which the data is to be sent to
+ * @param[in] rawPacket The data packet to be sent
+ * @param[in] len The length of the packet data in bytes
+ * @param[in] logList The std::list of leaks to be added.
+ *
+ * @return An error code
+ * @since Tizen 4.0
+ */
+ int PgAddLeakLog(const int userId, const int pId, const char *destination, const void *rawPacket, const size_t len, const std::list<leak_log_insert_data_s> &logList) const;
+
+ /**
+ * @brief get the current parsing rules for the application
+ *
+ * @param[in] userId The ID of the user
+ * @param[in] pId The process ID of the application
+ * @param[out] currentRules A std::list of rules for the user and application
+ *
+ * @note The rules can be updated at any time while the application is running.
+ * @see DlpRuleChangeNotification::addDlpClient()
+ * @return An error code
+ * @since Tizen 4.0
+ */
+ int PgGetDlpCurrentRules(const int userId, const int pId, std::list<current_rules_s> ¤tRules) const;
+};
+
+#endif // _PRIVACYGUARDDLP_H_
*/
#include "DlpLogsManager.h"
-#include "PrivacyGuardClient.h"
+#include "PrivacyGuardDlp.h"
#include "Utils.h"
std::mutex DlpLogsManager::m_singletonMutex;
DlpLogsManager::DlpLogsManager(void)
{
pthread_t notify_thread;
- m_privacyGuardClient = PrivacyGuardClient::getInstance();
+ m_privacyGuardDlp = PrivacyGuardDlp::getInstance();
// launch leak log send thread
m_leakLogSendMutex.lock();
entry.len = len;
entry.rlist = rules;
- // check if we have only ALLOW actions on the rules list
- for (auto &it : rules) {
- if (it.action != PRIV_GUARD_DLP_ACTION_ALLOW) {
- // if we have any rule different from ALLOW we need to parse now
- res = ParseAndLogLeakNow(entry);
- break;
- }
- }
+ /** This verification is not necessary in current implementation
+ * as it supports only ALLOW action.
+ * // check if we have only ALLOW actions on the rules list
+ * for (auto &it : rules) {
+ * if (it.action != PRIV_GUARD_DLP_ACTION_ALLOW) {
+ * // if we have any rule different from ALLOW we need to parse now
+ * res = ParseAndLogLeakNow(entry);
+ * break;
+ * }
+ *}
+ */
if (!entry.rlist.empty() || !entry.llist.empty()) {
// add entry to the m_logQueue to be processed when the thread awakes
void*
DlpLogsManager::LeakLogSendThread()
{
+ uid_t pid = getpid();
uid_t uid = getuid();
for (;;) {
// with new entries, try to process them
m_logQueueMutex.lock();
- for (auto &it : m_logQueue) {
+ for (auto it = m_logQueue.begin(); it != m_logQueue.end(); it++) {
+ m_logQueueMutex.unlock();
// if packet has not been parsed yet, parse now
- if (!it.rlist.empty())
- ParseAndLogLeakNow(it);
+ if (!it->rlist.empty())
+ ParseAndLogLeakNow(*it);
+
+ if (!it->llist.empty())
+ m_privacyGuardDlp->PgAddLeakLog(uid, pid, it->hostname.c_str(), it->mem, it->len, it->llist);
- if (!it.llist.empty())
- m_privacyGuardClient->PgAddLeakLog(uid, it.hostname.c_str(), it.mem, it.len, it.llist);
+ m_logQueueMutex.lock();
}
// all entries processed, call clear destroying each element from queue
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
+#include "PrivacyGuardDlp.h"
#include "DlpRulesManager.h"
#include "Utils.h"
DlpRulesManager::DlpRulesManager(void)
{
pthread_t notify_thread;
- m_privacyGuardClient = PrivacyGuardClient::getInstance();
+ m_privacyGuardDlp = PrivacyGuardDlp::getInstance();
// Launch privacy guard notification thread
m_rulesMutex.lock();
S_IRWXU |
S_IRGRP | S_IWGRP |
S_IROTH | S_IWOTH,
- 0);
+ 0);
umask(umask_value);
// Get rules from server for the first time
- m_privacyGuardClient->PgGetDlpCurrentRules(uid, pid, m_currentRules);
+ m_privacyGuardDlp->PgGetDlpCurrentRules(uid, pid, m_currentRules);
if (semaphore == SEM_FAILED) {
PG_LOGE("errro unlink sem: %s - %s", sem_name, strerror_r(errno, buf, sizeof(buf)));
// Get rules from server
m_rulesMutex.lock();
- m_privacyGuardClient->PgGetDlpCurrentRules(uid, pid, m_currentRules);
+ m_privacyGuardDlp->PgGetDlpCurrentRules(uid, pid, m_currentRules);
}
return NULL;
+++ /dev/null
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * @file PrivacyChecker.cpp
- */
-
-#include <algorithm>
-#include <memory>
-#include <sqlite3.h>
-#include <dbus/dbus-glib-lowlevel.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <privilege_info.h>
-#include "PrivacyChecker.h"
-#include "PrivacyIdInfo.h"
-#include "PrivacyGuardClient.h"
-#include "SocketClient.h"
-#include "Utils.h"
-
-#define BUF_SIZE 256
-
-bool PrivacyChecker::m_isInitialized = false;
-bool PrivacyChecker::m_isMonitorEnable = false;
-std::map < std::string, bool >PrivacyChecker::m_privacyCache;
-std::map < std::string, std::map < std::string, bool > > PrivacyChecker::m_privacyInfoCache;
-std::map < std::string, int > PrivacyChecker::m_monitorPolicyCache;
-std::mutex PrivacyChecker::m_cacheMutex;
-std::mutex PrivacyChecker::m_dbusMutex;
-std::mutex PrivacyChecker::m_initializeMutex;
-std::string PrivacyChecker::m_pkgId;
-DBusConnection* PrivacyChecker::m_pDBusConnection;
-GMainLoop* PrivacyChecker::m_pLoop = NULL;
-GMainContext* PrivacyChecker::m_pHandlerGMainContext = NULL;
-const int MAX_LOCAL_BUF_SIZE = 128;
-pthread_t PrivacyChecker::m_signalThread;
-
-int
-PrivacyChecker::initialize(void)
-{
- if (m_isInitialized) {
- return PRIV_GUARD_ERROR_SUCCESS;
- }
-
- std::lock_guard < std::mutex > guard(m_cacheMutex);
-
- int res = initMonitorPolicyCache();
- TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "Failed to update cache (%d)", res);
-
- res = initializeGMain();
- TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "Failed to initialize() (%d)", res);
-
- return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-int
-PrivacyChecker::initializeGMain(void)
-{
- std::unique_lock<std::mutex> initlock(m_initializeMutex);
-
- TryReturn(!m_isInitialized, PRIV_GUARD_ERROR_SUCCESS, , "Already Initalized");
-
- m_pHandlerGMainContext = g_main_context_new();
- TryReturn(m_pHandlerGMainContext != NULL, PRIV_GUARD_ERROR_SYSTEM_ERROR, , "cannot create m_pHandlerGMainContext");
-
- m_pLoop = g_main_loop_new(m_pHandlerGMainContext, FALSE);
- TryReturn(m_pLoop != NULL, PRIV_GUARD_ERROR_SYSTEM_ERROR, , "cannot create m_pLoop");
-
- std::unique_lock<std::mutex> lock(m_dbusMutex);
- char buf[BUF_SIZE];
- int res = pthread_create(&m_signalThread, NULL, &runSignalListenerThread, NULL);
- TryReturn(res >= 0, PRIV_GUARD_ERROR_SYSTEM_ERROR, errno = res;, "Failed to create listener thread :%s", strerror_r(res, buf, sizeof(buf)));
-
- m_isInitialized = true;
-
- return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-void
-PrivacyChecker::printMonitorPolicyCache(void)
-{
- for(std::map<std::string, int>::iterator itr = m_monitorPolicyCache.begin(); itr != m_monitorPolicyCache.end(); itr++) {
- PG_LOGD("PRIVACY string : %s", itr->first.c_str());
- PG_LOGD("PRIVACY monitor_policy : %d", itr->second);
- }
-}
-
-int
-PrivacyChecker::initMonitorPolicyCache(void)
-{
- std::list < std::pair < std::string, int > > monitorPolicyList;
-
- int retval = PrivacyGuardClient::getInstance()->PgGetAllMonitorPolicy(monitorPolicyList);
- if(retval == PRIV_GUARD_ERROR_SUCCESS && !monitorPolicyList.empty()) {
- m_monitorPolicyCache.insert(monitorPolicyList.begin(), monitorPolicyList.end());
- } else {
- PG_LOGD("ret: [%d], monitorPolicyList size: [%d]", retval, monitorPolicyList.size());
- }
-
- return retval;
-}
-
-int
-PrivacyChecker::getMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, int &monitorPolicy)
-{
- int res = PRIV_GUARD_ERROR_SUCCESS;
- PG_LOGD("m_isInitialized: %d", m_isInitialized);
-
- if (m_isInitialized == false) {
- initialize();
- }
-
- std::string userPkgIdPrivacyId = std::to_string(userId) + std::string("|") + packageId + std::string("|") + privacyId;
- PG_LOGD("key: %s", userPkgIdPrivacyId.c_str());
- std::map<std::string, int>::iterator itr = m_monitorPolicyCache.find(userPkgIdPrivacyId);
-
- if(itr != m_monitorPolicyCache.end()) {
- monitorPolicy = itr->second;
- } else {
- monitorPolicy = 0;
- res = PRIV_GUARD_ERROR_NO_DATA;
- }
-
- return res;
-}
-
-void
-PrivacyChecker::checkMonitorByPrivilege(const std::string privilegeId)
-{
- PG_LOGD("checkMonitorByPrivilege called with privilege: [%s]", privilegeId.c_str());
-
- if (privilege_info_is_privacy(privilegeId.c_str())) {
- m_isMonitorEnable = true;
- } else {
- PG_LOGD("[%s] is not related to a privacy.", privilegeId.c_str());
- m_isMonitorEnable = false;
- }
-}
-
-void*
-PrivacyChecker::runSignalListenerThread(void* pData)
-{
- pthread_detach(pthread_self());
-
- PG_LOGI("Running g main loop for signal");
-
- initializeDbus();
-
- g_main_loop_run(m_pLoop);
-
- finalizeDbus();
-
- pthread_exit(NULL);
-
- return (void*) 0;
-}
-
-int
-PrivacyChecker::initializeDbus(void)
-{
- DBusError error;
- dbus_error_init(&error);
-
- m_pDBusConnection = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error);
- TryReturn(m_pDBusConnection != NULL, PRIV_GUARD_ERROR_SYSTEM_ERROR, dbus_error_free(&error), "dbus_bus_get_private [%s] : %d", PRIV_GUARD_ERROR_SYSTEM_ERROR);
-
- dbus_connection_setup_with_g_main(m_pDBusConnection, m_pHandlerGMainContext);
- std::unique_ptr < char[] > pRule(new char[MAX_LOCAL_BUF_SIZE]);
-
- snprintf(pRule.get(), MAX_LOCAL_BUF_SIZE, "path='%s',type='signal',interface='%s'", DBUS_PATH.c_str(), DBUS_SIGNAL_INTERFACE.c_str());
- dbus_bus_add_match(m_pDBusConnection, pRule.get(), &error);
- TryReturn(!dbus_error_is_set(&error), PRIV_GUARD_ERROR_SYSTEM_ERROR, dbus_error_free(&error), "dbus_bus_add_match[%s] : %d", error.message, PRIV_GUARD_ERROR_SYSTEM_ERROR);
-
- dbus_bool_t r = dbus_connection_add_filter(m_pDBusConnection, handleNotification, NULL, NULL);
- TryReturn(r, PRIV_GUARD_ERROR_SYSTEM_ERROR, , "dbus_connection_add_filter: %d", PRIV_GUARD_ERROR_SYSTEM_ERROR);
-
- return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-int
-PrivacyChecker::finalizeDbus(void)
-{
- dbus_connection_remove_filter(m_pDBusConnection, handleNotification, NULL);
- dbus_connection_close(m_pDBusConnection);
- m_pDBusConnection = NULL;
-
- return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-
-DBusHandlerResult
-PrivacyChecker::handleNotification(DBusConnection* connection, DBusMessage* message, void* user_data)
-{
- DBusError error;
- dbus_bool_t r;
- dbus_error_init(&error);
-
- char* pPkgId;
- char* pPrivacyId;
-
- if (dbus_message_is_signal(message, DBUS_SIGNAL_INTERFACE.c_str(), DBUS_SIGNAL_SETTING_CHANGED.c_str())) {
- r = dbus_message_get_args(message, &error,
- DBUS_TYPE_STRING, &pPkgId,
- DBUS_TYPE_STRING, &pPrivacyId,
- DBUS_TYPE_INVALID);
- TryReturn(r, DBUS_HANDLER_RESULT_NOT_YET_HANDLED, , "Fail to get data : %s", error.message);
-
- std::lock_guard < std::mutex > guard(m_cacheMutex);
-
- if (std::string(pPkgId) == m_pkgId)
- {
- PG_LOGI("Current app pkg privacy information updated");
- updateCache(m_pkgId, pPrivacyId, m_privacyCache);
- //printCache();
- }
-
- std::map < std::string, std::map < std::string, bool > > :: iterator iter = m_privacyInfoCache.find(std::string(pPkgId));
- if (iter != m_privacyInfoCache.end()) {
- PG_LOGI("Current pkg privacy is in cache");
- updateCache(std::string(pPkgId), pPrivacyId, iter->second);
- }
- } else if (dbus_message_is_signal(message, DBUS_SIGNAL_INTERFACE.c_str(), DBUS_SIGNAL_PKG_REMOVED.c_str())) {
- r = dbus_message_get_args(message, &error,
- DBUS_TYPE_STRING, &pPkgId,
- DBUS_TYPE_INVALID);
- TryReturn(r, DBUS_HANDLER_RESULT_NOT_YET_HANDLED, , "Fail to get data : %s", error.message);
-
- std::lock_guard < std::mutex > guard(m_cacheMutex);
-
- std::map < std::string, std::map < std::string, bool > > :: iterator iter = m_privacyInfoCache.find(std::string(pPkgId));
- if (iter != m_privacyInfoCache.end()) {
- m_privacyInfoCache.erase(iter);
- }
- }
-
- // This event is not only for specific handler. All handlers of daemons should be check it and handle it.
- return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
-}
-
-int
-PrivacyChecker::check(const std::string privacyId, std::map < std::string, bool >& privacyMap)
-{
- TryReturn(m_isInitialized, PRIV_GUARD_ERROR_NOT_INITIALIZED, , "Not initialized");
-
- std::map < std::string, bool >::iterator iter;
-
- iter = privacyMap.find(privacyId);
- if (iter == privacyMap.end()) {
- PG_LOGD("The application cannot access the privacy inforamtion.");
- return PRIV_GUARD_ERROR_USER_NOT_CONSENTED;
- } else if (!iter->second) {
- PG_LOGD("User does not consented to access the privacy information");
- return PRIV_GUARD_ERROR_USER_NOT_CONSENTED;
- }
-
- return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-int
-PrivacyChecker::check(const std::string privacyId)
-{
- if (!m_isInitialized)
- return PRIV_GUARD_ERROR_NOT_INITIALIZED;
-
- std::lock_guard < std::mutex > guard(m_cacheMutex);
-
- int res = check(privacyId, m_privacyCache);
-
- return res;
-}
-
-int
-PrivacyChecker::check(const std::string pkgId, const std::string privacyId)
-{
- if (!m_isInitialized)
- initialize();
-
- std::lock_guard < std::mutex > guard(m_cacheMutex);
- int res;
-
- std::map < std::string, std::map < std::string, bool > >::iterator iter = m_privacyInfoCache.find(pkgId);
- if (iter == m_privacyInfoCache.end() )
- {
- std::map < std::string, bool > pkgCacheMap;
- res = updateCache(pkgId, pkgCacheMap);
- TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, PRIV_GUARD_ERROR_DB_ERROR, , "Failed to update cache : %d", res);
-
- m_privacyInfoCache.insert(std::map <std::string, std::map<std::string, bool>>::value_type(std::string(pkgId), pkgCacheMap));
- iter = m_privacyInfoCache.find(pkgId);
- }
-
- if (iter->second.size() == 0)
- {
- return PRIV_GUARD_ERROR_USER_NOT_CONSENTED;
- }
-
- res = check(privacyId, iter->second);
-
- return res;
-}
-
-int
-PrivacyChecker::finalize(void)
-{
- std::lock_guard<std::mutex> guard(m_cacheMutex);
- m_privacyCache.clear();
- m_privacyInfoCache.clear();
-
- if (m_pLoop != NULL)
- {
- g_main_loop_quit(m_pLoop);
- m_pLoop = NULL;
- }
-
- if (m_pHandlerGMainContext != NULL)
- {
- g_main_context_unref(m_pHandlerGMainContext);
- m_pHandlerGMainContext = NULL;
- }
-
- m_isInitialized = false;
-
- return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-void
-PrivacyChecker::printCache(void)
-{
- std::map < std::string, bool >::const_iterator iter = m_privacyCache.begin();
- for (; iter != m_privacyCache.end(); ++iter)
- {
- PG_LOGD(" %s : %d", iter->first.c_str(), iter->second);
- }
-}
-
-int
-PrivacyChecker::updateCache(const std::string pkgId, std::string privacyId, std::map < std::string, bool >& pkgCacheMap)
-{
- static const std::string PrivacyQuery = "SELECT IS_ENABLED from PrivacyInfo where PKG_ID=? and PRIVACY_ID=?";
-
- openDb(PRIVACY_DB_PATH, pDbH, SQLITE_OPEN_READONLY);
- prepareDb(pDbH, PrivacyQuery.c_str(), pPrivacyStmt);
- int res = sqlite3_bind_text(pPrivacyStmt.get(), 1, pkgId.c_str(), -1, SQLITE_TRANSIENT);
- TryReturn(res == 0, PRIV_GUARD_ERROR_DB_ERROR, , "sqlite3_bind_text : %d", res);
-
- res = sqlite3_bind_text(pPrivacyStmt.get(), 2, privacyId.c_str(), -1, SQLITE_TRANSIENT);
- TryReturn(res == 0, PRIV_GUARD_ERROR_DB_ERROR, , "sqlite3_bind_text : %d", res);
-
- while ( sqlite3_step(pPrivacyStmt.get()) == SQLITE_ROW )
- {
- bool privacyEnabled = sqlite3_column_int(pPrivacyStmt.get(), 0) > 0 ? true : false;
-
- PG_LOGD("Set result : %s : %d", privacyId.c_str(), privacyEnabled);
- pkgCacheMap.erase(privacyId);
- pkgCacheMap.insert(std::map < std::string, bool >::value_type(privacyId, privacyEnabled));
- }
-
- return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-int
-PrivacyChecker::updateCache(std::string pkgId, std::map < std::string, bool >& pkgCacheMap)
-{
- static const std::string PrivacyQuery = "SELECT PRIVACY_ID, IS_ENABLED from PrivacyInfo where PKG_ID=?";
-
- pkgCacheMap.clear();
-
- openDb(PRIVACY_DB_PATH, pDbH, SQLITE_OPEN_READONLY);
- prepareDb(pDbH, PrivacyQuery.c_str(), pPrivacyStmt);
- int res = sqlite3_bind_text(pPrivacyStmt.get(), 1, pkgId.c_str(), -1, SQLITE_TRANSIENT);
- TryReturn(res == SQLITE_OK, PRIV_GUARD_ERROR_DB_ERROR, , "sqlite3_bind_text : %d", res);
-
- while ( (res = sqlite3_step(pPrivacyStmt.get())) == SQLITE_ROW )
- {
- const char* privacyId = reinterpret_cast < const char* > (sqlite3_column_text(pPrivacyStmt.get(), 0));
- bool privacyEnabled = sqlite3_column_int(pPrivacyStmt.get(), 1) > 0 ? true : false;
-
- pkgCacheMap.insert(std::map < std::string, bool >::value_type(std::string(privacyId), privacyEnabled));
-
- PG_LOGD("Privacy found : %s %d", privacyId, privacyEnabled);
- }
- return PRIV_GUARD_ERROR_SUCCESS;
-}
--- /dev/null
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <aul.h>
+#include "PrivacyGuardDlp.h"
+#include "SocketClient.h"
+
+#undef __READ_DB_IPC__
+
+std::mutex PrivacyGuardDlp::m_singletonMutex;
+PrivacyGuardDlp* PrivacyGuardDlp::m_pInstance = NULL;
+const std::string PrivacyGuardDlp::INTERFACE_NAME("PrivacyInfoService");
+
+PrivacyGuardDlp::PrivacyGuardDlp()
+{
+}
+
+/**
+ * @callgraph
+ */
+PrivacyGuardDlp*
+PrivacyGuardDlp::getInstance()
+{
+ std::lock_guard<std::mutex> guard(m_singletonMutex);
+ if (m_pInstance == NULL)
+ m_pInstance = new(std::nothrow) PrivacyGuardDlp();
+ return m_pInstance;
+}
+
+/**
+ * @callgraph
+ */
+int
+PrivacyGuardDlp::PgAddLeakLog(const int userId, const int pId, const char *destination, const void *rawPacket, const size_t len, const std::list<leak_log_insert_data_s> &logList) const
+{
+ if (destination == NULL || rawPacket == NULL)
+ return PRIV_GUARD_ERROR_INVALID_PARAMETER;
+
+ int result = PRIV_GUARD_ERROR_SUCCESS;
+ SocketClient socketClient(INTERFACE_NAME);
+ packet_data_s packetData = { (int)len, (void *)rawPacket};
+
+ int res = socketClient.connect();
+ TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "connect : %d", res);
+
+ res = socketClient.call("PgAddLeakLog", userId, pId, destination, packetData, logList, &result);
+ TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, socketClient.disconnect(), "call : %d", res);
+
+ res = socketClient.disconnect();
+ TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "disconnect : %d", res);
+
+ return result;
+}
+
+/**
+ * @callgraph
+ */
+int
+PrivacyGuardDlp::PgGetDlpCurrentRules(const int userId, const int pId, std::list<current_rules_s> ¤tRules) const
+{
+ int result = PRIV_GUARD_ERROR_SUCCESS;
+ SocketClient socketClient(INTERFACE_NAME);
+
+ int res = socketClient.connect();
+ TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "connect : %d", res);
+
+ currentRules.clear();
+ res = socketClient.call("PgGetDlpCurrentRules", userId, pId, &result, ¤tRules);
+ TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, socketClient.disconnect(), "call : %d", res);
+
+ res = socketClient.disconnect();
+ TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "disconnect : %d", res);
+
+ return result;
+}
*/
void privacy_guard_dlp_init(void)
{
- DlpRulesManager::getInstance();
- DlpLogsManager::getInstance();
+// DlpRulesManager::getInstance();
+// DlpLogsManager::getInstance();
PG_LOGD("Initializing DLP");
+ pid_t pid = getpid();
+ uid_t uid = getuid();
+ PG_LOGD("privacy_guard_dlp_check_leak - pid: %d - uid: %d", pid, uid);
}
/**
*/
PgDlpResult privacy_guard_dlp_check_leak(const char *hostname, char * const mem, size_t len)
{
+
+ pid_t pid = getpid();
+ uid_t uid = getuid();
+ PG_LOGD("privacy_guard_dlp_check_leak - pid: %d - uid: %d", pid, uid);
+
+ DlpRulesManager::getInstance();
+ DlpLogsManager::getInstance();
+
#ifdef PERF_TEST
struct timespec tp_before, tp_after;
long interval;
clock_gettime(CLOCK_REALTIME, &tp_before);
#endif
current_rules_list rules;
- PgDlpResult res;
DlpRulesManager *pRules = DlpRulesManager::getInstance();
DlpLogsManager *pLogs = DlpLogsManager::getInstance();
/* return DENY if called with NULL values or zero len */
if (hostname == NULL || mem == NULL || len == 0) {
PG_LOGE("DLP check leak received and empty request, message denied");
- return PRIV_GUARD_DLP_RESULT_DENY;
+ return PRIV_GUARD_DLP_RESULT_ALLOW;
}
/* get cached rules from server */
return PRIV_GUARD_DLP_RESULT_ALLOW;
}
- res = pLogs->ParseAndLogLeak(hostname, mem, len, rules);
+ pLogs->ParseAndLogLeak(hostname, mem, len, rules);
#ifdef PERF_TEST
clock_gettime(CLOCK_REALTIME, &tp_after);
PG_LOGD("DLP check time: %ld us", interval);
#endif
-#ifdef _PRIVACY_GUARD_DEBUG
- if (res == PRIV_GUARD_DLP_RESULT_ALLOW) {
- PG_LOGD("Packet allowed");
- } else {
- PG_LOGD("Packet denied");
- }
-#endif
-
- return res;
+ return PRIV_GUARD_DLP_RESULT_ALLOW;
}
#define _PRIVACY_GUARD_COMMON_H_
#include <sqlite3.h>
-#include <db-util.h>
#include <stdbool.h>
#endif // _PRIVACY_GUARD_COMMON_H_
typedef struct _leak_log_insert_common_data_s {
int user_id;
- char application_id[LEN_APPLICATION_ID];
- char application_name[LEN_APPLICATION_NAME];
- char application_version[LEN_APPLICATION_VERSION];
- char application_icon[LEN_APPLICATION_ICON];
- char package_id[LEN_PACKAGE_ID];
+ int pid;
char destination[LEN_DESTINATION];
packet_data_s pkt_data;
} leak_log_insert_common_data_s;
typedef std::list<current_rules_s> current_rules_list;
+typedef struct _privacy_semaphore_app_info_s {
+ char application_id[LEN_APPLICATION_ID];
+ char application_name[LEN_APPLICATION_NAME];
+ char application_version[LEN_APPLICATION_VERSION];
+ char application_icon[LEN_APPLICATION_ICON];
+ char package_id[LEN_PACKAGE_ID];
+} privacy_semaphore_app_info_s;
+
typedef struct _privacy_semaphore_s {
int pid;
sem_t *sem;
+ privacy_semaphore_app_info_s app_info;
} privacy_semaphore_s;
typedef struct _custom_rule_s {
int make_call(T *outvalue)
{
return m_socketConnector->read(outvalue);
- }
+ }
private:
std::string m_serverAddress;
int res = read(&out.user_id);
TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
- // application ID
- res = read(out.application_id, LEN_APPLICATION_ID);
- TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
-
- // application name
- res = read(out.application_name, LEN_APPLICATION_NAME);
- TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
-
- // application version
- res = read(out.application_version, LEN_APPLICATION_VERSION);
- TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
-
- // application icon
- res = read(out.application_icon, LEN_APPLICATION_ICON);
- TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
-
- // package ID
- res = read(out.package_id, LEN_PACKAGE_ID);
+ // pid
+ res = read(&out.pid);
TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
// destination
#include <memory>
#include <string>
#include <unistd.h>
-#include <db-util.h>
#include "privacy_guard_utils.h"
// debug print /////////////////////////////////////////////
LOGE(logFormat, res); \
expr; \
return r; \
- } else {;}
+ } else {; }
#define TryReturn(condition, r, expr, ...) \
var = NULL; \
}
-auto StmtDeleter = [&](sqlite3_stmt* pPtr) { sqlite3_reset(pPtr); sqlite3_finalize(pPtr); };
-auto DbDeleter = [&](sqlite3* pPtr) { /*sqlite3_close(pPtr);*/ db_util_close(pPtr); };
-
-#define setStmtToUniquePtr(x, y) std::unique_ptr < sqlite3_stmt, decltype(StmtDeleter) > x (y, StmtDeleter);
-#define setDbToUniquePtr(x, y) std::unique_ptr < sqlite3, decltype(DbDeleter) > x (y, DbDeleter);
-
-#define openDb(dbpath, pHandler, mode) sqlite3* pHandler##Temp = NULL; \
- { \
- /*int res = sqlite3_open_v2(dbpath, &pHandler##Temp, mode , NULL);*/ \
- int res = db_util_open_with_options(dbpath, &pHandler##Temp, mode, NULL); \
- TryCatchResLogReturn(res == SQLITE_OK, , PRIV_GUARD_ERROR_DB_ERROR, "db_util_open_with_options : %d", res); \
- } \
- setDbToUniquePtr(pHandler, pHandler##Temp); \
-
static const int MAX_DATABASE_RETRY_COUNT = 5;
static const int SLEEP_TIME = 50000;
-#define prepareDb(pHandler, sql, pStmt) sqlite3_stmt* pStmt##Temp; \
+#define prepareDb(pHandler, sql, pStmt) sqlite3_stmt *pStmt##Temp; \
{ \
int res = SQLITE_OK; \
for (int dbRetryCount = 0; dbRetryCount < MAX_DATABASE_RETRY_COUNT; dbRetryCount++) { \
* @param[in] src a pointer to the string to be copied from.
* @param[in] dstsize the maximum number of bytes to be copied.
*/
- extern "C" void pg_strlcpy(char *dst, const char *src, size_t dstsize);
-
- #endif //_PRIVACY_GUARD_UTILS_H_
\ No newline at end of file
+extern "C" void pg_strlcpy(char *dst, const char *src, size_t dstsize);
+
+ #endif //_PRIVACY_GUARD_UTILS_H_
std::list<DlpPcre> *complist = (std::list<DlpPcre> *)ptr;
int subStrVec[30];
- int rc, i, offs, idx = 0;
+ int i, offs, idx = 0;
offs = 0;
for (auto it = complist->begin(); it != complist->end();) {
/* Try to find the regex in aLineToMatch, and report results. */
- rc = pcre_exec((*it).compiled,
+ int rc = pcre_exec((*it).compiled,
(*it).extra,
data,
length, // length of string
int flags;
if ( (flags = fcntl(m_socketFd, F_GETFL, 0)) == -1 )
flags = 0;
- res = fcntl(m_socketFd, F_SETFL, flags | O_NONBLOCK);
+ fcntl(m_socketFd, F_SETFL, flags | O_NONBLOCK);
TryReturn( m_socketFd != -1, PRIV_GUARD_ERROR_IPC_ERROR, , "fcntl : %s", strerror_r(errno, buf, sizeof(buf)));
bzero(&remote, sizeof(remote));
FD_ZERO(&allset);
FD_SET(m_socketFd, &allset);
- int ret;
unsigned int currentOffset = 0;
while (currentOffset < num)
timeout.tv_sec = READ_TIEMOUT_SEC;
timeout.tv_nsec = READ_TIMEUOT_NSEC;
rset = allset;
+ int ret;
if ( (ret = pselect(maxFd, &rset, NULL, NULL, &timeout, NULL)) == -1 )
{
FD_ZERO(&allset);
FD_SET(m_socketFd, &allset);
- int res;
ssize_t writeRes;
unsigned int currentOffset = 0;
timeout.tv_nsec = WRITE_TIMEOUT_NSEC;
wset = allset;
- if ( (res = pselect(maxFd, NULL, &wset, NULL, &timeout, NULL)) == -1 )
+ if ( pselect(maxFd, NULL, &wset, NULL, &timeout, NULL) == -1 )
{
if(errno == EINTR)
continue;
CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
-#PROJECT(privacy-guard-client)
+#PROJECT(privacy-guard-setting)
SET(PG_INCLUDE_PATH ${PROJECT_SOURCE_DIR}/include)
-SET(PRIVACY_GUARD_CLIENT_HEADERS
+SET(PRIVACY_GUARD_SETTING_HEADERS
${PG_INCLUDE_PATH}/privacy_guard_client.h
${PG_INCLUDE_PATH}/privacy_guard_client_types.h
)
-INSTALL(FILES ${PRIVACY_GUARD_CLIENT_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard)
+INSTALL(FILES ${PRIVACY_GUARD_SETTING_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard)
/**
* @file privacy_guard_client.h
- * @brief API for privacy-guard-client (C / C++)
+ * @brief API for privacy-guard-setting (C / C++)
*/
#ifndef _PRIVACY_GUARD_CLIENT_H_
* @param[in] rule_id The existing rule ID
* @param[in] action The new action to be taken (allow, deny, sanitize)
* @param[in] pattern_id The new pattern ID
- * @param[in] name The new rule name
- * @param[in] description The new rule description
- * @param[in] application_id The new app id
+ * @param[in] name The new rule name
+ * @param[in] description The new rule description
+ * @param[in] application_id The new app id
*
* @return the result of operation (ERRORCODE : success, ....)
*/
<request>
<domain name="_" />
</request>
-</manifest>
+</manifest>
\ No newline at end of file
--- /dev/null
+<manifest>
+ <request>
+ <domain name="_" />
+ </request>
+</manifest>
<request>
<domain name="_" />
</request>
-</manifest>
+</manifest>
\ No newline at end of file
<request>
<domain name="_" />
</request>
-</manifest>
+</manifest>
\ No newline at end of file
--- /dev/null
+<manifest>
+ <request>
+ <domain name="_" />
+ </request>
+</manifest>
--- /dev/null
+<manifest>
+ <request>
+ <domain name="_" />
+ </request>
+</manifest>
Name: privacy-guard-server
-Version: 0.9.6
+Version: 0.9.7
Release: 1
License: Apache-2.0
Summary: Privacy Management
Source2: privacy-guard-server.socket
Source1001: privacy-guard-server.manifest
Source1002: privacy-guard-server-devel.manifest
-Source1003: privacy-guard-client.manifest
-Source1004: privacy-guard-client-devel.manifest
+Source1003: privacy-guard-setting.manifest
+Source1004: privacy-guard-setting-devel.manifest
+Source1005: privacy-guard-client.manifest
+Source1006: privacy-guard-client-devel.manifest
BuildRequires: cmake
BuildRequires: gettext-tools
BuildRequires: pkgconfig(capi-base-common)
-BuildRequires: pkgconfig(db-util)
BuildRequires: pkgconfig(dbus-1)
BuildRequires: pkgconfig(dbus-glib-1)
BuildRequires: pkgconfig(dlog)
%description -n privacy-guard-server-devel
privacy-guard server devel
+%package -n privacy-guard-setting
+Summary: Privacy Guard Setting
+
+%description -n privacy-guard-setting
+privacy-guard setting
+
+%package -n privacy-guard-setting-devel
+Summary: Privacy Guard setting devel
+Requires: privacy-guard-setting = %{version}
+
+%description -n privacy-guard-setting-devel
+Privacy Management(development files)
+
%package -n privacy-guard-client
Summary: Privacy Guard Client
Requires: privacy-guard-server = %{version}
cp %{SOURCE1002} .
cp %{SOURCE1003} .
cp %{SOURCE1004} .
+cp %{SOURCE1005} .
+cp %{SOURCE1006} .
%build
%{!?build_type:%define build_type "Release"}
%postun -p /sbin/ldconfig
+%post -n privacy-guard-setting -p /sbin/ldconfig
+%postun -n privacy-guard-setting -p /sbin/ldconfig
+
%post -n privacy-guard-client -p /sbin/ldconfig
%postun -n privacy-guard-client -p /sbin/ldconfig
%files -n privacy-guard-server-devel
%{_libdir}/pkgconfig/privacy-guard-server.pc
+%files -n privacy-guard-setting
+%defattr(-,root,root,-)
+%license LICENSE.APLv2
+%manifest privacy-guard-setting.manifest
+%{_libdir}/libprivacy-guard-setting.so*
+%{_sysconfdir}/package-manager/parserlib/libprivileges.so
+
+%files -n privacy-guard-setting-devel
+%defattr(-,root,root,-)
+%manifest privacy-guard-setting-devel.manifest
+%{_includedir}/privacy_guard/setting/*
+%{_includedir}/privacy_guard/privacy_guard_client_types.h
+%{_includedir}/privacy_guard/privacy_guard_client.h
+%{_libdir}/pkgconfig/privacy-guard-setting.pc
+
%files -n privacy-guard-client
%defattr(-,root,root,-)
%license LICENSE.APLv2
%manifest privacy-guard-client.manifest
%{_libdir}/libprivacy-guard-client.so*
-%{_sysconfdir}/package-manager/parserlib/libprivileges.so
%files -n privacy-guard-client-devel
%defattr(-,root,root,-)
%manifest privacy-guard-client-devel.manifest
-%{_includedir}/*
+%{_includedir}/privacy_guard/client/*
+%{_includedir}/privacy_guard/privacy_guard_client_types.h
+%{_includedir}/privacy_guard/privacy_guard_dlp.h
%{_libdir}/pkgconfig/privacy-guard-client.pc
%files -n tc-privacy-guard
%{_bindir}/tc-privacy-guard
%{_bindir}/tc-dlp
+%{_bindir}/tc-ahocorasick
/usr/include/pkgmgr
/usr/include/package_manager
/usr/include/dlog
- "${CMAKE_SOURCE_DIR}/client/inc/"
+ "${CMAKE_SOURCE_DIR}/setting/inc/"
"${CMAKE_SOURCE_DIR}/common/inc/"
"${CMAKE_SOURCE_DIR}/include/"
)
## Create Library
ADD_LIBRARY (${this_target} SHARED ${${this_target}_SOURCE_FILES} )
-ADD_DEPENDENCIES(${this_target} privacy-guard-client)
+ADD_DEPENDENCIES(${this_target} privacy-guard-setting)
## SET LINKER FLAGS
SET(CMAKE_SHARED_LINKER_FLAGS -Wl,--no-undefined)
TARGET_LINK_LIBRARIES(${this_target} ${pkg_LDFLAGS} ${pkg_LIBRARIES})
-TARGET_LINK_LIBRARIES(${this_target} "-lprivacy-guard-client" "-L../client" )
+TARGET_LINK_LIBRARIES(${this_target} "-lprivacy-guard-setting" "-L../setting" )
ADD_CUSTOM_COMMAND(TARGET ${this_target}
POST_BUILD
void destroy_char_list(char** ppList, int size)
{
- int i = 0;
-
if (ppList) {
- for (i = 0; i < size; ++i) {
+ for (int i = 0; i < size; ++i) {
if (ppList[i])
free(ppList[i]);
}
}
extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
int PKGMGR_PARSER_PLUGIN_PRE_INSTALL(const char *packageId)
{
return 0;
}
extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
int PKGMGR_PARSER_PLUGIN_INSTALL(xmlDocPtr docPtr, const char* packageId)
{
if (packageId == NULL) {
LOGE("Failed to get privilege value.");
return -EINVAL;
} else {
- privilegeList.push_back(std::string( reinterpret_cast<char*> (pPrivilege)));
+ privilegeList.push_back(std::string(reinterpret_cast<char*> (pPrivilege)));
LOGD("Succeeded to get privilege value.");
}
}
}
extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
int PKGMGR_PARSER_PLUGIN_POST_INSTALL(const char *packageId)
{
return 0;
}
extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
int PKGMGR_PARSER_PLUGIN_PRE_UNINSTALL(const char *packageId)
{
return 0;
}
extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
int PKGMGR_PARSER_PLUGIN_UNINSTALL(xmlDocPtr docPtr, const char* packageId)
{
if (packageId == NULL) {
}
extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
int PKGMGR_PARSER_PLUGIN_POST_UNINSTALL(const char *packageId)
{
return 0;
}
extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
int PKGMGR_PARSER_PLUGIN_PRE_UPGRADE(const char *packageId)
{
return 0;
}
extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
int PKGMGR_PARSER_PLUGIN_UPGRADE(xmlDocPtr docPtr, const char* packageId)
{
if (packageId == NULL) {
}
extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
int PKGMGR_PARSER_PLUGIN_POST_UPGRADE(const char *packageId)
{
return 0;
--- /dev/null
+prefix=@PREFIX@
+exec_prefix=@EXEC_PREFIX@
+libdir=@LIBDIR@
+includedir=/usr/include
+
+Name: @PC_NAME@
+Description: @PC_DESCRIPTION@
+Version: @VERSION@
+Libs: -L${libdir} @PC_LDFLAGS@
+Cflags: @PC_CFLAGS@
+Requires:
SET(INCLUDEDIR "\${prefix}/include")
INCLUDE(FindPkgConfig)
-pkg_check_modules(pkgs REQUIRED dlog sqlite3 dbus-1 dbus-glib-1 db-util pkgmgr-info capi-system-info
+pkg_check_modules(pkgs REQUIRED dlog sqlite3 dbus-1 dbus-glib-1 pkgmgr-info capi-system-info
libtzplatform-config security-privilege-manager cynara-monitor security-manager aul
capi-telephony capi-network-connection capi-network-wifi capi-location-manager
contacts-service2)
/**
* @brief start the thread which returns real time updated data
*
- * @return true if the thread started without error
+ * @return true if the thread started without error
* @see stop()
* @since Tizen 3.0
*/
void loadMyProfile(void);
void loadInfo(const int userId);
static void *startLocation(void *_this);
+ bool waitForModemReady(const telephony_h handle) const;
connection_h m_connection;
std::list<char *> m_imei_list;
/**
* @brief add a new client to list of clients to inform about rule changes
* @param[in] pId The process id of the client to be added
+ * @param[in] userId The user id of the client to be added
+ * @param[in] appId The buffer to write the application id
*
* @return the result of operation (ERRORCODE : success, ....)
* @since Tizen 3.0
*/
- int addDlpClient(int pId);
+ int addDlpClient(int pId, int userId, char *appId);
+
+ /**
+ * @brief get the application info for the pid
+ * @param[in] pId The process id of the client look of info
+ * @param[out] app_info The privacy_semaphore_app_info_s struct related to pid
+ *
+ * @return the result of operation (ERRORCODE : success, ....)
+ * @since Tizen 3.0
+ */
+ int getAppInfo(int pId, privacy_semaphore_app_info_s **app_info);
/**
* @brief send notification to all registered clients that a rule may have changed
/**
* @brief get the list of current rules
* @param[in] userId The user ID to get the rules for
- * @param[in] AppId The application name (or empty string)
* @param[in] pId The process ID, to be added to the list of rule change notification clients
* @param[out] rules The rules which were retrieved
*
* @return the result of operation (ERRORCODE : success, ....)
* @since Tizen 4.0
*/
- int PgGetDlpCurrentRules(const int userId, const char *AppId, const int pId, std::list<current_rules_s> &rules);
+ int PgGetDlpCurrentRules(const int userId, const int pId, std::list<current_rules_s> &rules);
/**
* @brief retrieve the list of email addresses for the specified user
class PrivacyInfoService {
private:
- inline static std::string getInterfaceName(void)
+ static inline std::string getInterfaceName(void)
{
return "PrivacyInfoService";
}
public:
-static void registerCallbacks(SocketService* pSocketService) {
+static void registerCallbacks(SocketService* pSocketService)
+{
pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgAddPrivacyAccessLog"), PgAddPrivacyAccessLog);
pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgAddMonitorPolicy"), PgAddMonitorPolicy);
pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgDeleteLogsByPackageId"), PgDeleteLogsByPackageId);
{
//PG_LOGD("Running get entries thread");
- int res = -1;
-
pthread_detach(pthread_self());
while (exit_flag == false) {
if (monitor_entries) {
}
// returned when the cynara buffer is full or cynara_monitor_entries_flush() is called from another thread
- res = cynara_monitor_entries_get(p_cynara_monitor, &monitor_entries);
+ int res = cynara_monitor_entries_get(p_cynara_monitor, &monitor_entries);
if(res != CYNARA_API_SUCCESS){
PG_LOGE("cynara_monitor_entries_get() is failed. [%d]", res);
#if defined(USE_PTHREAD_WAITING)
CynaraService::updateDb(cynara_monitor_entry **monitor_entries)
{
cynara_monitor_entry **entryIter = monitor_entries;
- const char *user = NULL, *client = NULL, *privilege = NULL;
+ const char *user = NULL, *client = NULL;
const timespec *timestamp = NULL;
uid_t user_id;
std::string privacyId;
time_t date;
- int res = -1;
char *pkg_name = NULL, *app_name = NULL;
while (*entryIter != nullptr) {
- privilege = cynara_monitor_entry_get_privilege(*entryIter);
+ const char *privilege = cynara_monitor_entry_get_privilege(*entryIter);
TryReturn(privilege != NULL, PRIV_GUARD_ERROR_SYSTEM_ERROR, , "Privilege Id in the entry is NULL");
// change from privilege to privacy
privacyId.clear();
- res = PrivacyIdInfo::getPrivacyIdFromPrivilege(privilege, privacyId);
+ int res = PrivacyIdInfo::getPrivacyIdFromPrivilege(privilege, privacyId);
//PG_LOGD("########## res: [%d] privilege: [%s] privacy: [%s]", res, privilege, privacyId.c_str());
if (res != PRIV_GUARD_ERROR_NO_DATA) {
//PG_LOGD("#Privilege: [%s]", privilege);
int
CynaraService::stop(void)
{
- char buf[BUF_SIZE];
int ret;
// set thread exit condition
}
if((ret = pthread_kill(m_cynaraThread, m_signalToClose)) < 0) {
+ char buf[BUF_SIZE];
+
PG_LOGE("pthread_kill(): %s", strerror_r(ret, buf, sizeof(buf)));
return PRIV_GUARD_ERROR_IPC_ERROR;
}
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
+#include <aul.h>
+#include <pkgmgr-info.h>
#include "DlpRuleChangeNotification.h"
#include "Utils.h"
}
int
-DlpRuleChangeNotification::addDlpClient(int pId)
+DlpRuleChangeNotification::addDlpClient(int pId, int userId, char *appId)
{
int res = PRIV_GUARD_ERROR_SUCCESS;
bool first_request_by_pid = true;
- char sem_name[sizeof(PRIVACY_SEM_INITVAL)+5];
- char buf[BUF_SIZE];
std::lock_guard<std::mutex> guard(m_singletonMutex);
for (auto it = m_semaphore_list.begin(); it != m_semaphore_list.end();) {
if (it->pid == pId) {
// Process found, no need to add it to sem list
first_request_by_pid = false;
+ strncpy(appId, it->app_info.application_id, LEN_APPLICATION_ID);
} else {
// Just checking if the process still exists, no signal is sent
if (kill(it->pid, 0) == -1 && errno == ESRCH) {
}
if (first_request_by_pid) {
+ char sem_name[sizeof(PRIVACY_SEM_INITVAL)+5];
// First request from process, to add it to sem list
snprintf(sem_name, sizeof(PRIVACY_SEM_INITVAL)+5, PRIVACY_SEM_INITVAL, pId);
privacy_semaphore_s ps;
+ pkgmgrinfo_appinfo_h appinfo = NULL;
+ pkgmgrinfo_pkginfo_h pkginfo = NULL;
+ char *data = NULL;
+
+ // load application ID
+ ps.app_info.application_id[0] = '\0';
+ int ret = aul_app_get_appid_bypid(pId, ps.app_info.application_id, LEN_APPLICATION_ID);
+ if (ret == 0) {
+ // load application info
+ ret = pkgmgrinfo_appinfo_get_usr_appinfo(ps.app_info.application_id, userId, &appinfo);
+ if (ret == 0) {
+ // load application name
+ ret = pkgmgrinfo_appinfo_get_label(appinfo, &data);
+ if (ret == 0)
+ pg_strlcpy(ps.app_info.application_name, data, LEN_APPLICATION_NAME);
+
+ // load package ID
+ ret = pkgmgrinfo_appinfo_get_pkgid(appinfo, &data);
+ if (ret == 0)
+ pg_strlcpy(ps.app_info.package_id, data, LEN_PACKAGE_ID);
+
+ // load application icon
+ ret = pkgmgrinfo_appinfo_get_icon(appinfo, &data);
+ if (ret == 0)
+ pg_strlcpy(ps.app_info.application_icon, data, LEN_APPLICATION_ICON);
+
+ // load package info
+ ret = pkgmgrinfo_pkginfo_get_pkginfo(ps.app_info.package_id, &pkginfo);
+ if (ret == 0) {
+ // load application version
+ ret = pkgmgrinfo_pkginfo_get_version(pkginfo, &data);
+ if (ret == 0)
+ pg_strlcpy(ps.app_info.application_version, data, LEN_APPLICATION_VERSION);
+
+ pkgmgrinfo_pkginfo_destroy_pkginfo(pkginfo);
+ }
+
+ pkgmgrinfo_appinfo_destroy_appinfo(appinfo);
+ }
+ }
+
+ strncpy(appId, ps.app_info.application_id, LEN_APPLICATION_ID);
ps.sem = sem_open(sem_name, 0);
if (ps.sem == SEM_FAILED) {
+ char buf[BUF_SIZE];
+
PG_LOGE("errro opening sem: %s - %s", sem_name, strerror_r(errno, buf, sizeof(buf)));
res = errno;
} else {
}
int
+DlpRuleChangeNotification::getAppInfo(int pId, privacy_semaphore_app_info_s **app_info) {
+ for (auto &it: m_semaphore_list) {
+ if (it.pid == pId) {
+ *app_info = &(it.app_info);
+ return PRIV_GUARD_ERROR_SUCCESS;
+ }
+ }
+ return PRIV_GUARD_ERROR_NO_DATA;
+}
+
+int
DlpRuleChangeNotification::notifyDlpClients()
{
char buf[BUF_SIZE];
PG_LOGI("Starting DLP");
res = DlpPrivacyInfoData::getInstance()->start();
- if (res != true)
+ if ((bool) res != true)
PG_LOGE("Can not start DLP");
return res;
void
PrivacyGuardDb::openSqliteDB(void)
{
- int res = -1;
- res = sqlite3_open_v2(PRIVACY_DB_PATH, &m_sqlHandler, SQLITE_OPEN_READWRITE, NULL);
+ int res = sqlite3_open_v2(PRIVACY_DB_PATH, &m_sqlHandler, SQLITE_OPEN_READWRITE, NULL);
if(res == SQLITE_OK) {
PG_LOGI("monitor db is opened successfully");
//sqlite3_wal_autocheckpoint(m_sqlHandler, 1);
return PRIV_GUARD_ERROR_INVALID_PARAMETER;
}
- int res = -1;
-
// check monitor policy using userId, packageId, privacyId
int monitorPolicy;
- res = PgGetMonitorPolicy(userId, packageId, privacyId, monitorPolicy);
+ int res = PgGetMonitorPolicy(userId, packageId, privacyId, monitorPolicy);
TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "PgGetMonitorPolicy is failed: [%d]", res);
if (monitorPolicy == 0) {
PG_LOGD("Monitor Policy is 0. So skip it. UserId:[%d], PrivacyId:[%s], PackageId:[%s], Policy:[%d]", userId, privacyId.c_str(), packageId.c_str(), monitorPolicy);
int
PrivacyGuardDb::PgCheckPrivacyPackage(const int userId, const std::string packageId, bool &isPrivacyPackage)
{
- int res = -1;
char buf[BUF_SIZE];
snprintf(buf, BUF_SIZE, "SELECT COUNT(*) FROM MonitorPolicy WHERE USER_ID=? AND PKG_ID=?");
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
m_dbMutex.lock();
int count = -1;
// step
- if ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) {
+ if (sqlite3_step(m_stmt) == SQLITE_ROW) {
count = sqlite3_column_int(m_stmt, 0);
}
int
PrivacyGuardDb::PgForeachTotalPrivacyCountOfPackage(const int userId, const int startDate, const int endDate, std::list < std::pair < std::string, int > >& packageInfoList)
{
- int res = -1;
char buf[BUF_SIZE];
sqlite3_stmt* infoStmt;
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
// [CYNARA] Flush Entries
int
PrivacyGuardDb::PgForeachTotalPrivacyCountOfPrivacy(const int userId, const int startDate, const int endDate, std::list < std::pair < std::string, int > >& privacyInfoList)
{
- int res = -1;
char buf[BUF_SIZE];
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
// [CYNARA] Flush Entries
PrivacyGuardDb::PgForeachPrivacyCountByPrivacyId(const int userId, const int startDate, const int endDate,
const std::string privacyId, std::list < std::pair < std::string, int > >& packageInfoList)
{
- int res = -1;
sqlite3_stmt* infoStmt;
char buf[BUF_SIZE];
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
// [CYNARA] Flush Entries
PrivacyGuardDb::PgForeachPrivacyCountByPackageId(const int userId, const int startDate, const int endDate,
const std::string packageId, std::list < std::pair < std::string, int > >& privacyInfoList)
{
- int res = -1;
char buf[BUF_SIZE];
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
// [CYNARA] Flush Entries
int
PrivacyGuardDb::PgGetMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, int& monitorPolicy)
{
- int res = -1;
char buf[BUF_SIZE];
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
snprintf(buf, BUF_SIZE, "SELECT MONITOR_POLICY FROM MonitorPolicy WHERE USER_ID=? AND PKG_ID=? AND PRIVACY_ID=?");
// step
monitorPolicy = 0;
- if ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) {
+ if (sqlite3_step(m_stmt) == SQLITE_ROW) {
monitorPolicy = sqlite3_column_int(m_stmt, 0);
}
int
PrivacyGuardDb::PgForeachMonitorPolicyByPackageId(const int userId, const std::string packageId, std::list <privacy_data_s>& privacyInfoList)
{
- int res = -1;
char buf[BUF_SIZE];
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
snprintf(buf, BUF_SIZE, "SELECT DISTINCT PRIVACY_ID, MONITOR_POLICY FROM MonitorPolicy WHERE USER_ID=? AND PKG_ID=?");
TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
// step
- while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) {
+ while (sqlite3_step(m_stmt) == SQLITE_ROW) {
char* tmp_data = (char*)sqlite3_column_text(m_stmt, 0);
if(tmp_data == NULL) {
continue;
int
PrivacyGuardDb::PgForeachPackageIdUsingPrivacy(const int userId, std::list < std::string > &packageList)
{
- int res = -1;
char buf[BUF_SIZE];
snprintf(buf, BUF_SIZE, "SELECT DISTINCT PKG_ID FROM MonitorPolicy WHERE USER_ID=?");
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
m_dbMutex.lock();
TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res);
// step
- while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) {
+ while (sqlite3_step(m_stmt) == SQLITE_ROW) {
char* p_data = (char*)sqlite3_column_text(m_stmt, 0);
if(p_data == NULL) {
continue;
TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock();, PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res);
// step
- while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) {
+ while (sqlite3_step(m_stmt) == SQLITE_ROW) {
char *package_id = (char*)sqlite3_column_text(m_stmt, 0);
char *privacy_id = (char*)sqlite3_column_text(m_stmt, 1);
if(package_id == NULL || privacy_id == NULL) {
int
PrivacyGuardDb::PgForeachPackageInfoByPrivacyId(const int userId, const std::string privacyId, std::list < package_data_s > &packageInfoList)
{
- int res = -1;
sqlite3_stmt* infoStmt;
time_t start_date, today_midnight, end_date;
struct tm date;
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
int
PrivacyGuardDb::PgUpdateMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, const int monitorPolicy)
{
- int res = -1;
char buf[BUF_SIZE];
snprintf(buf, BUF_SIZE, "UPDATE MonitorPolicy SET MONITOR_POLICY=? WHERE USER_ID=? AND PKG_ID=? AND PRIVACY_ID=?");
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
m_dbMutex.lock();
int
PrivacyGuardDb::PgAddMainMonitorPolicy(const int userId)
{
- int res = -1;
-
static const std::string QUERY_INSERT = std::string("INSERT INTO MainMonitorPolicy(USER_ID) VALUES(?)");
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
m_dbMutex.lock();
int
PrivacyGuardDb::PgUpdateMainMonitorPolicy(const int userId, const int mainMonitorPolicy)
{
- int res = -1;
char buf[BUF_SIZE];
snprintf(buf, BUF_SIZE, "UPDATE MainMonitorPolicy SET MAIN_MONITOR_POLICY=? WHERE USER_ID=? ");
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
m_dbMutex.lock();
int
PrivacyGuardDb::PgGetMainMonitorPolicy(const int userId, int &mainMonitorPolicy)
{
- int res = -1;
char buf[BUF_SIZE];
snprintf(buf, BUF_SIZE, "SELECT MAIN_MONITOR_POLICY FROM MainMonitorPolicy WHERE USER_ID=?");
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
m_dbMutex.lock();
int
PrivacyGuardDb::PgDeleteMainMonitorPolicyByUserId(const int userId)
{
- int res = -1;
-
static const std::string QUERY_DELETE = std::string("DELETE FROM MainMonitorPolicy WHERE USER_ID=?");
///////////////////////////////////////////////////
// prepare privacy monitor policy for global apps
///////////////////////////////////////////////////
- res = prepareGlobalPackagePolicy(userId);
+ int res = prepareGlobalPackagePolicy(userId);
TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
m_dbMutex.lock();
const char *insertl = "INSERT INTO DlpLeakLog(REQUEST_ID, PATTERN_ID, ACTION, LEAK_OFFSET, LEAK_LEN) "
"VALUES(?, ?, ?, ?, ?)";
+ privacy_semaphore_app_info_s *app_info;
+ if(DlpRuleChangeNotification::getInstance() == NULL || PRIV_GUARD_ERROR_SUCCESS !=
+ DlpRuleChangeNotification::getInstance()->getAppInfo(data.pid, &app_info))
+ return PRIV_GUARD_ERROR_DB_ERROR;
+
m_dbMutex.lock();
// initialize
res = sqlite3_bind_int(m_stmt, 2, time(NULL));
TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res);
- res = sqlite3_bind_text(m_stmt, 3, data.application_name, -1, SQLITE_TRANSIENT);
+ res = sqlite3_bind_text(m_stmt, 3, app_info->application_name, -1, SQLITE_TRANSIENT);
TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
- res = sqlite3_bind_text(m_stmt, 4, data.application_icon, -1, SQLITE_TRANSIENT);
+ res = sqlite3_bind_text(m_stmt, 4, app_info->application_icon, -1, SQLITE_TRANSIENT);
TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
- res = sqlite3_bind_text(m_stmt, 5, data.application_id, -1, SQLITE_TRANSIENT);
+ res = sqlite3_bind_text(m_stmt, 5, app_info->application_id, -1, SQLITE_TRANSIENT);
TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
- res = sqlite3_bind_text(m_stmt, 6, data.application_version, -1, SQLITE_TRANSIENT);
+ res = sqlite3_bind_text(m_stmt, 6, app_info->application_version, -1, SQLITE_TRANSIENT);
TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
- res = sqlite3_bind_text(m_stmt, 7, data.package_id, -1, SQLITE_TRANSIENT);
+ res = sqlite3_bind_text(m_stmt, 7, app_info->package_id, -1, SQLITE_TRANSIENT);
TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
res = sqlite3_bind_text(m_stmt, 8, data.destination, -1, SQLITE_TRANSIENT);
PrivacyGuardDb::PgGetLeakLogDetails(int userId, int logId, leak_log_get_detail_data_s &logDetail)
{
int res = -1;
- int fragment_offset;
const char *query = "SELECT L.ACTION, RE.APP_ID, RE.APP_NAME, RE.APP_VERSION, RE.APP_ICON, RE.PKG_ID, " \
"RE.DESTINATION, P.NAME, P.CATEGORY_ID, LENGTH(CAST(RE.RAW_PACKET AS BLOB)), " \
" CAST(RE.RAW_PACKET AS BLOB), L.LEAK_OFFSET, " \
// step
if (sqlite3_step(m_stmt) == SQLITE_ROW) {
+ int fragment_offset;
+
logDetail.action = (PgDlpAction)sqlite3_column_int(m_stmt, 0);
pg_strlcpy(logDetail.application_id, (const char *)sqlite3_column_text(m_stmt, 1), LEN_APPLICATION_ID);
pg_strlcpy(logDetail.application_name, (const char *)sqlite3_column_text(m_stmt, 2), LEN_APPLICATION_NAME);
int PrivacyGuardDb::purgeUnusedDeletedPatterns()
{
- int patternId;
const char *query1 = "SELECT ID FROM DlpPatterns WHERE STATE=?";
const char *query2 = "SELECT ID FROM DlpLeakLog WHERE PATTERN_ID=?";
const char *query3 = "DELETE FROM DlpPatterns WHERE ID=?";
while (sqlite3_step(m_stmt) == SQLITE_ROW) {
// step through all patterns marked as STATE=PRIV_GUARD_DLP_PATTERN_STATE_DELETED
- patternId = sqlite3_column_int(m_stmt, 0);
+ int patternId = sqlite3_column_int(m_stmt, 0);
// query leak logs to see if any has a reference to the pattern. Otherwise we delete the pattern
// prepare
{
int res = -1;
const char *query = "UPDATE DlpProfile SET ENABLED=?, PROFILE=?, KEEP_LOG_DAYS=? WHERE USER_ID=?";
- const char *insert = "INSERT INTO DlpProfile(USER_ID, ENABLED, PROFILE, KEEP_LOG_DAYS) VALUES(?, ?, ?, ?)";
m_dbMutex.lock();
// insert profile if not found
if (sqlite3_changes(m_sqlHandler) == 0) {
+ const char *insert = "INSERT INTO DlpProfile(USER_ID, ENABLED, PROFILE, KEEP_LOG_DAYS) VALUES(?, ?, ?, ?)";
+
sqlite3_finalize(m_stmt);
// prepare
}
int
-PrivacyGuardDb::PgGetDlpCurrentRules(const int userId, const char *appId, const int pId, std::list<current_rules_s> &rules)
+PrivacyGuardDb::PgGetDlpCurrentRules(const int userId, const int pId, std::list<current_rules_s> &rules)
{
int res = -1;
char query[256];
+ char appId[LEN_APPLICATION_ID] = {0};
dlp_profile_s profile;
if(DlpRuleChangeNotification::getInstance() != NULL)
- DlpRuleChangeNotification::getInstance()->addDlpClient(pId);
+ DlpRuleChangeNotification::getInstance()->addDlpClient(pId, userId, appId);
+ else
+ return PRIV_GUARD_ERROR_DB_ERROR;
// get current profile
PgGetDlpProfile(userId, profile);
const PgDlpPatternType type = (PgDlpPatternType)sqlite3_column_int(m_stmt, 4);
// rule found, replace it
- for (it = rules.begin(); it != rules.end(); it++) {
+ for (it = rules.begin(); it != rules.end(); ++it) {
if (it->pattern_id == pattern_id && it->type == type) {
// replaces a general rule with an app specific one
it->id = sqlite3_column_int(m_stmt, 0);
PrivacyGuardDb::PgGetAccountEmails(const int userId, std::set<std::string> &emails)
{
sqlite3 *sqlHandler = NULL;
- int res = -1;
sqlite3_stmt *stmt;
const char *email_query = "SELECT DISTINCT email_address FROM account";
char account_uid_db_path[sizeof("%d/.account.db") + 8];
//////////////////////////////
snprintf(account_uid_db_path, sizeof("%d/.account.db") + 8, "%d/.account.db", userId);
- res = sqlite3_open_v2(tzplatform_mkpath(TZ_SYS_DB, account_uid_db_path), &sqlHandler, SQLITE_OPEN_READONLY, NULL);
+ int res = sqlite3_open_v2(tzplatform_mkpath(TZ_SYS_DB, account_uid_db_path), &sqlHandler, SQLITE_OPEN_READONLY, NULL);
TryCatchResLogReturn(res == SQLITE_OK, ;, PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_open_v2 : %d", res);
// prepare
int PrivacyGuardDb::markUnusedPatterns(int ruleId, int newPatternId, sqlite3_stmt* update_stmt)
{
- int res = -1;
- int patternId, patternCount;
+ int patternId;
const char *query1 = "SELECT PATTERN_ID FROM DlpRules WHERE ID=?";
- const char *query2 = "SELECT COUNT(*) FROM DlpRules WHERE PATTERN_ID=?";
- const char *query3 = "UPDATE DlpPatterns SET STATE=? WHERE ID=? AND STATE=?";
// get old PATTERN_ID
// prepare
- res = sqlite3_prepare_v2(m_sqlHandler, query1, -1, &m_stmt, NULL);
+ int res = sqlite3_prepare_v2(m_sqlHandler, query1, -1, &m_stmt, NULL);
TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res);
// bind
sqlite3_finalize(update_stmt);
if (newPatternId != patternId) {
+ const char *query2 = "SELECT COUNT(*) FROM DlpRules WHERE PATTERN_ID=?";
+
// rule was deleted or updated
// get count of PATTERN_ID now
res = sqlite3_step(m_stmt);
TryCatchResLogReturn(res == SQLITE_ROW, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_step : %d", res);
- patternCount = sqlite3_column_int(m_stmt, 0);
+ int patternCount = sqlite3_column_int(m_stmt, 0);
sqlite3_finalize(m_stmt);
if (patternCount == 0) {
+ const char *query3 = "UPDATE DlpPatterns SET STATE=? WHERE ID=? AND STATE=?";
+
// we can delete the pattern as we were the only one using it
// for now we just mark it as STATE=PRIV_GUARD_DLP_PATTERN_STATE_DELETED. This is because some log details may refer to it.
// We will delete these patterns from the database during leak log cleanup.
PrivacyGuardDb::PgForeachDlpRules(int userId, int profile, std::list<get_custom_rule_s> &rules)
{
int res = -1;
- const char *queryc = "SELECT R.ID, R.ACTION, R.PATTERN_ID, R.NAME, R.DESCRIPTION, P.NAME, P.DESCRIPTION, R.APP_ID, "
- "(SELECT COUNT(LL.ID) FROM DlpLeakLog AS LL WHERE LL.PATTERN_ID == R.PATTERN_ID) FROM DlpRules AS R, "
- "DlpPatterns AS P WHERE R.PATTERN_ID=P.ID AND R.USER_ID=? AND PROFILE=?";
-
- const char *query = "SELECT R.ID, R.ACTION, R.PATTERN_ID, R.NAME, R.DESCRIPTION, P.NAME, P.DESCRIPTION, R.APP_ID, "
- "(SELECT COUNT(LL.ID) FROM DlpLeakLog AS LL WHERE LL.PATTERN_ID == R.PATTERN_ID) FROM DlpRules AS R, "
- "DlpPatterns AS P WHERE R.PATTERN_ID=P.ID AND PROFILE=?";
m_dbMutex.lock();
// prepare
if (profile == PRIV_GUARD_DLP_PROFILE_CUSTOM) {
+ const char *queryc = "SELECT R.ID, R.ACTION, R.PATTERN_ID, R.NAME, R.DESCRIPTION, P.NAME, P.DESCRIPTION, R.APP_ID, "
+ "(SELECT COUNT(LL.ID) FROM DlpLeakLog AS LL WHERE LL.PATTERN_ID == R.PATTERN_ID) FROM DlpRules AS R, "
+ "DlpPatterns AS P WHERE R.PATTERN_ID=P.ID AND R.USER_ID=? AND PROFILE=?";
+
res = sqlite3_prepare_v2(m_sqlHandler, queryc, -1, &m_stmt, NULL);
TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res);
res = sqlite3_bind_int(m_stmt, 2, profile);
TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res);
} else {
+ const char *query = "SELECT R.ID, R.ACTION, R.PATTERN_ID, R.NAME, R.DESCRIPTION, P.NAME, P.DESCRIPTION, R.APP_ID, "
+ "(SELECT COUNT(LL.ID) FROM DlpLeakLog AS LL WHERE LL.PATTERN_ID == R.PATTERN_ID) FROM DlpRules AS R, "
+ "DlpPatterns AS P WHERE R.PATTERN_ID=P.ID AND PROFILE=?";
+
res = sqlite3_prepare_v2(m_sqlHandler, query, -1, &m_stmt, NULL);
TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res);
return m_pInstance;
}
+
#include <contacts.h>
#include <wifi.h>
+#include <chrono>
+#include <thread>
+
#include "Utils.h"
#include "DlpPrivacyInfoData.h"
#include "PrivacyGuardDb.h"
contacts_list_destroy(contact_list, true);
}
+bool
+DlpPrivacyInfoData::waitForModemReady(const telephony_h handle) const
+{
+ constexpr int max_retries{ 25 };
+ constexpr auto retry_delay = std::chrono::milliseconds(20);
+ int ret = TELEPHONY_ERROR_NONE - 1;
+ int retry = 0;
+
+ while (retry < max_retries && ret != TELEPHONY_ERROR_NONE) {
+ telephony_modem_power_status_e modem_power_status;
+ ret = telephony_modem_get_power_status(handle, &modem_power_status);
+ if (TELEPHONY_ERROR_NONE != ret) {
+ PG_LOGE("telephony_modem_get_power_status() failed. Error=%d", ret);
+ std::this_thread::sleep_for(retry_delay);
+ }
+ ++retry;
+ }
+
+ return ret == TELEPHONY_ERROR_NONE;
+}
+
void
DlpPrivacyInfoData::loadInfo(const int userId)
{
// Loading IMEIs, phone numbers
if (m_handle_list.handle == NULL && telephony_init(&m_handle_list) == TELEPHONY_ERROR_NONE) {
for (unsigned int i = 0; i < m_handle_list.count; i++) {
- ret = telephony_modem_get_imei(m_handle_list.handle[i], &imei);
- if (ret == TELEPHONY_ERROR_NONE && imei && strlen(imei))
- m_imei_list.push_back(imei);
+ if (waitForModemReady(m_handle_list.handle[i])) {
+ ret = telephony_modem_get_imei(m_handle_list.handle[i], &imei);
+ if (ret == TELEPHONY_ERROR_NONE && imei && strlen(imei))
+ m_imei_list.push_back(imei);
+ } else {
+ PG_LOGE("Modem is not ready. IMEI can not be monitored.");
+ }
ret = telephony_sim_get_subscriber_number(m_handle_list.handle[i], &phoneno);
if (ret == TELEPHONY_ERROR_NONE && phoneno && strlen(phoneno))
PrivacyInfoService::PgGetDlpCurrentRules(SocketConnection* pConnector)
{
int userId = 0;
- char appId[LEN_PACKAGE_ID];
int pId = 0;
std::list<current_rules_s> templateRules;
std::list<current_rules_s> rules;
pConnector->read(&userId);
- int res = pConnector->read(appId, LEN_PACKAGE_ID);
- if (res != PRIV_GUARD_ERROR_SUCCESS) {
- PG_LOGE("fail : pConnector->read(appId, LEN_PACKAGE_ID) (%d)", res);
- return;
- }
pConnector->read(&pId);
- int result = PrivacyGuardDb::getInstance()->PgGetDlpCurrentRules(userId, appId, pId, templateRules);
+ int result = PrivacyGuardDb::getInstance()->PgGetDlpCurrentRules(userId, pId, templateRules);
// replace all rule templates
if (result == PRIV_GUARD_ERROR_SUCCESS)
--- /dev/null
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+#PROJECT(privacy-guard-setting)
+
+FIND_PACKAGE(Threads REQUIRED)
+
+SET(CMAKE_INSTALL_PREFIX /usr)
+SET(PREFIX ${CMAKE_INSTALL_PREFIX})
+SET(EXEC_PREFIX "\${prefix}")
+SET(LIBDIR ${LIB_INSTALL_DIR})
+SET(INCLUDEDIR ${INCLUDE_INSTALL_DIR})
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(privacy-guard-setting REQUIRED dlog sqlite3 dbus-1 dbus-glib-1 libtzplatform-config libpcre)
+
+FOREACH(flag ${pkgs_CFLAGS})
+ SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(CMAKE_C_FLAGS_PROFILING " -g -pg")
+SET(CMAKE_CXX_FLAGS_PROFILING " -std=c++0x -g -pg")
+SET(CMAKE_C_FLAGS_DEBUG " -g")
+SET(CMAKE_CXX_FLAGS_DEBUG " -std=c++0x -g")
+SET(CMAKE_C_FLAGS_RELEASE " -g")
+SET(CMAKE_CXX_FLAGS_RELEASE " -std=c++0x -g")
+SET(CMAKE_C_FLAGS_CCOV " -g --coverage")
+SET(CMAKE_CXX_FLAGS_CCOV " -std=c++0x -g --coverage")
+
+SET(setting_src_dir "${CMAKE_SOURCE_DIR}/setting/src")
+SET(setting_include_dir "${CMAKE_SOURCE_DIR}/setting/inc/")
+SET(common_src_dir "${CMAKE_SOURCE_DIR}/common/src/")
+SET(common_include_dir "${CMAKE_SOURCE_DIR}/common/inc/")
+SET(extern_include_dir "${CMAKE_SOURCE_DIR}/include/")
+SET(ahocorasick_dir "${CMAKE_SOURCE_DIR}/ahocorasick/")
+
+## Additional flag
+ADD_DEFINITIONS("-fvisibility=hidden")
+ADD_DEFINITIONS("-Wall -Werror")
+ADD_DEFINITIONS("-DDLOG_ERROR_ENABLED")
+ADD_DEFINITIONS("-D_PRIVACY_GUARD_DEBUG")
+
+###################################################################################################
+## for libprivacy-guard-setting
+INCLUDE_DIRECTORIES(${pkgs_INCLUDE_DIRS} ${setting_include_dir} ${common_include_dir} ${extern_include_dir})
+SET(PRIVACY_GUARD_SETTING_SOURCES
+ ${common_src_dir}/SocketClient.cpp
+ ${common_src_dir}/SocketConnection.cpp
+ ${common_src_dir}/SocketStream.cpp
+ ${common_src_dir}/PrivacyIdInfo.cpp
+ ${common_src_dir}/DlpUtils.cpp
+ ${common_src_dir}/Utils.cpp
+ ${common_src_dir}/privacy_guard_utils.c
+ ${setting_src_dir}/PrivacyGuardClient.cpp
+ ${setting_src_dir}/privacy_guard_client.cpp
+ ${ahocorasick_dir}/ahocorasick.c
+ ${ahocorasick_dir}/node.c
+ )
+SET(PRIVACY_GUARD_SETTING_HEADERS
+ ${setting_include_dir}/PrivacyGuardClient.h
+ ${setting_include_dir}/privacy_guard_client_internal.h
+ )
+SET(PRIVACY_GUARD_EXTERN_HEADERS
+ ${extern_include_dir}/privacy_guard_client.h
+ ${extern_include_dir}/privacy_guard_client_types.h
+ )
+
+SET(PRIVACY_GUARD_SETTING_LDFLAGS " -module -avoid-version ")
+SET(PRIVACY_GUARD_SETTING_CFLAGS " ${CFLAGS} -fPIC ")
+
+ADD_DEFINITIONS("-DLOG_TAG=\"PRIVACY-GUARD-SETTING\"")
+ADD_LIBRARY(privacy-guard-setting SHARED ${PRIVACY_GUARD_SETTING_SOURCES})
+TARGET_LINK_LIBRARIES(privacy-guard-setting -pthread ${pkgs_LDFLAGS} ${pkgs_LIBRARIES})
+SET_TARGET_PROPERTIES(privacy-guard-setting PROPERTIES COMPILE_FLAGS "${PRIVACY_GUARD_SETTING_CFLAGS}")
+SET_TARGET_PROPERTIES(privacy-guard-setting PROPERTIES SOVERSION ${API_VERSION})
+SET_TARGET_PROPERTIES(privacy-guard-setting PROPERTIES VERSION ${VERSION})
+###################################################################################################
+
+SET(PC_NAME privacy-guard-setting)
+SET(PC_DESCRIPTION "Privacy Guard Setting API")
+SET(PC_LDFLAGS -lprivacy-guard-setting -lpcre)
+SET(PC_CFLAGS -I\${includedir}/privacy_guard)
+
+CONFIGURE_FILE(../privacy-guard-setting.pc.in privacy-guard-setting.pc @ONLY)
+
+INSTALL(TARGETS privacy-guard-setting DESTINATION ${LIB_INSTALL_DIR} COMPONENT RuntimeLibraries)
+INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/privacy-guard-setting.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig)
+INSTALL(FILES ${PRIVACY_GUARD_SETTING_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard/setting)
+INSTALL(FILES ${PRIVACY_GUARD_EXTERN_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard)
sqlite3* m_sqlHandler;
sqlite3_stmt* m_stmt;
bool m_bDBOpen;
-char m_applicationId[LEN_APPLICATION_ID] = { 0 };
-char m_applicationName[LEN_APPLICATION_NAME] = { 0 };
-char m_applicationVersion[LEN_APPLICATION_VERSION] = { 0 };
-char m_applicationIcon[LEN_APPLICATION_ICON] = { 0 };
-char m_packageId[LEN_PACKAGE_ID] = { 0 };
static PrivacyGuardClient* m_pInstance;
static const std::string INTERFACE_NAME;
// DLP features
/**
- * @brief add a list of leak logs to the database
- *
- * @param[in] userId The ID of the user running the application
- * @param[in] destination The host which the data is to be sent to
- * @param[in] rawPacket The data packet to be sent
- * @param[in] len The length of the packet data in bytes
- * @param[in] logList The std::list of leaks to be added.
- *
- * @return An error code
- * @since Tizen 4.0
- */
-int PgAddLeakLog(const int userId, const char *destination, const void *rawPacket, const size_t len, const std::list<leak_log_insert_data_s> &logList) const;
-
-/**
* @brief get all logs from leaked packets.
*
* @param[in] userId The ID of the user
* @since Tizen 4.0
*/
int PgGetDlpCurrentRules(const int userId, const int pId, std::list<current_rules_s> ¤tRules) const;
-
+
/**
* @brief add a custom DLP rule for user userId
*
/**
* @brief add a new DLP pattern
*
- * @param[in] name Pattern name
- * @param[in] description Pattern description
- * @param[in] category Pattern category
- * @param[in] pattern The pattern to match
- * @param[in] type Pattern type (STRING, REGEX)
+ * @param[in] name Pattern name
+ * @param[in] description Pattern description
+ * @param[in] category Pattern category
+ * @param[in] pattern The pattern to match
+ * @param[in] type Pattern type (STRING, REGEX)
*
* @return the result of operation (ERRORCODE : success, ....)
*/
/**
* @file privacy_guard_client_internal.h
- * @brief Internal API for privacy-guard-client
+ * @brief Internal API for privacy-guard-setting
*/
#ifndef _PRIVACY_GUARD_CLIENT_INTERNAL_H_
#include <memory>
#include <fcntl.h>
#include <strings.h>
-#include <aul.h>
-#include <pkgmgr-info.h>
#include "Utils.h"
#include "DlpUtils.h"
#include "PrivacyGuardClient.h"
PrivacyGuardClient::PrivacyGuardClient(void):m_sqlHandler(NULL), m_stmt(NULL), m_bDBOpen(false)
{
- loadApplicationInfo();
int res = loadDlpCategories();
if (res != PRIV_GUARD_ERROR_SUCCESS) {
PG_LOGE("fail : loadDlpCategories (%d)", res);
return -1;
}
-void
-PrivacyGuardClient::loadApplicationInfo()
-{
- int ret;
- char *data = NULL;
- pkgmgrinfo_appinfo_h appinfo = NULL;
- pkgmgrinfo_pkginfo_h pkginfo = NULL;
-
- // load application ID
- ret = aul_app_get_appid_bypid(getpid(), m_applicationId, LEN_APPLICATION_ID);
- if (ret == 0) {
- // load application info
- ret = pkgmgrinfo_appinfo_get_usr_appinfo(m_applicationId, getuid(), &appinfo);
- if (ret == 0) {
- // load application name
- ret = pkgmgrinfo_appinfo_get_label(appinfo, &data);
- if (ret == 0)
- pg_strlcpy(m_applicationName, data, LEN_APPLICATION_NAME);
-
- // load package ID
- ret = pkgmgrinfo_appinfo_get_pkgid(appinfo, &data);
- if (ret == 0)
- pg_strlcpy(m_packageId, data, LEN_PACKAGE_ID);
-
- // load application icon
- ret = pkgmgrinfo_appinfo_get_icon(appinfo, &data);
- if (ret == 0)
- pg_strlcpy(m_applicationIcon, data, LEN_APPLICATION_ICON);
-
- // load package info
- ret = pkgmgrinfo_pkginfo_get_pkginfo(m_packageId, &pkginfo);
- if (ret == 0) {
- // load application version
- ret = pkgmgrinfo_pkginfo_get_version(pkginfo, &data);
- if (ret == 0)
- pg_strlcpy(m_applicationVersion, data, LEN_APPLICATION_VERSION);
-
- pkgmgrinfo_pkginfo_destroy_pkginfo(pkginfo);
- }
-
- pkgmgrinfo_appinfo_destroy_appinfo(appinfo);
- }
- }
-}
-
/**
* @callgraph
*/
void
PrivacyGuardClient::openSqliteDB(void)
{
- int res = -1;
- res = sqlite3_open_v2(PRIVACY_DB_PATH, &m_sqlHandler, SQLITE_OPEN_READWRITE, NULL);
+ int res = sqlite3_open_v2(PRIVACY_DB_PATH, &m_sqlHandler, SQLITE_OPEN_READWRITE, NULL);
if(res == SQLITE_OK) {
PG_LOGI("monitor db is opened successfully");
m_bDBOpen = true;
return result;
}
-/**
- * @callgraph
- */
-int
-PrivacyGuardClient::PgAddLeakLog(const int userId, const char *destination, const void *rawPacket, const size_t len, const std::list<leak_log_insert_data_s> &logList) const
-{
- if (destination == NULL || rawPacket == NULL)
- return PRIV_GUARD_ERROR_INVALID_PARAMETER;
-
- int result = PRIV_GUARD_ERROR_SUCCESS;
- SocketClient socketClient(INTERFACE_NAME);
- packet_data_s packetData = { (int)len, (void *)rawPacket};
-
- int res = socketClient.connect();
- TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "connect : %d", res);
-
- res = socketClient.call("PgAddLeakLog", userId, (const char *)m_applicationId,
- (const char *)m_applicationName, (const char *)m_applicationVersion,
- (const char *)m_applicationIcon, (const char *)m_packageId,
- destination, packetData, logList, &result);
- TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, socketClient.disconnect(), "call : %d", res);
-
- res = socketClient.disconnect();
- TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "disconnect : %d", res);
-
- return result;
-}
-
int
PrivacyGuardClient::PgForeachLeakLogs(const int userId, std::list<leak_log_get_data_s> &logList) const
{
TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "connect : %d", res);
currentRules.clear();
- res = socketClient.call("PgGetDlpCurrentRules", userId, (const char *)m_applicationId,
- pId, &result, ¤tRules);
+ res = socketClient.call("PgGetDlpCurrentRules", userId, pId, &result, ¤tRules);
TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, socketClient.disconnect(), "call : %d", res);
res = socketClient.disconnect();
/**
* @file privacy_guard_client.cpp
- * @brief API for privacy-guard-client (C / C++)
+ * @brief API for privacy-guard-setting (C / C++)
*/
#include <string.h>
#include <string>
#include <memory>
-#include "PrivacyChecker.h"
#include "PrivacyGuardClient.h"
#include "privacy_guard_client.h"
#include "privacy_guard_client_internal.h"
}
std::list <privacy_data_s> privacyInfoList;
- int retval = -1;
-
- retval = PrivacyGuardClient::getInstance()->PgForeachMonitorPolicyByPackageId(user_id, std::string(package_id), privacyInfoList);
+ int retval = PrivacyGuardClient::getInstance()->PgForeachMonitorPolicyByPackageId(user_id, std::string(package_id), privacyInfoList);
if (retval != PRIV_GUARD_ERROR_SUCCESS) {
PG_LOGE("Failed to do PrivacyGuardClient::PgForeachMonitorPolicyByPackageId() [%d]", retval);
return retval;
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License.
*/
/**
SET(TC1_NAME tc-privacy-guard)
SET(TC2_NAME tc-dlp)
SET(TC3_NAME tc-dlp-performance)
+SET(TC4_NAME tc-ahocorasick)
SET(TC1_SRCS ${TC1_NAME}.c)
SET(TC2_SRCS ${TC2_NAME}.c)
SET(TC3_SRCS ${TC3_NAME}.c)
+SET(TC4_SRCS ${TC4_NAME}.c)
-INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/client/inc ${CMAKE_SOURCE_DIR}/common/inc ${CMAKE_SOURCE_DIR}/common/src)
+INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/setting/inc ${CMAKE_SOURCE_DIR}/client/inc ${CMAKE_SOURCE_DIR}/common/inc ${CMAKE_SOURCE_DIR}/common/src)
SET(requires glib-2.0 dlog libpcre)
INCLUDE(FindPkgConfig)
ADD_EXECUTABLE(${TC1_NAME} ${TC1_SRCS} ${SOURCES})
ADD_EXECUTABLE(${TC2_NAME} ${TC2_SRCS} ${SOURCES})
ADD_EXECUTABLE(${TC3_NAME} ${TC3_SRCS} ${SOURCES})
+ADD_EXECUTABLE(${TC4_NAME} ${TC4_SRCS} ${SOURCES})
-TARGET_LINK_LIBRARIES(${TC1_NAME} "privacy-guard-client")
-TARGET_LINK_LIBRARIES(${TC2_NAME} "privacy-guard-client")
-TARGET_LINK_LIBRARIES(${TC3_NAME} "privacy-guard-client" "rt")
+TARGET_LINK_LIBRARIES(${TC1_NAME} "privacy-guard-setting")
+TARGET_LINK_LIBRARIES(${TC2_NAME} "privacy-guard-setting" "privacy-guard-client")
+TARGET_LINK_LIBRARIES(${TC3_NAME} "privacy-guard-setting" "privacy-guard-client" "rt")
+TARGET_LINK_LIBRARIES(${TC4_NAME} "privacy-guard-setting")
INSTALL(TARGETS ${TC1_NAME} DESTINATION /usr/bin)
INSTALL(TARGETS ${TC2_NAME} DESTINATION /usr/bin)
#INSTALL(TARGETS ${TC3_NAME} DESTINATION /usr/bin)
+INSTALL(TARGETS ${TC4_NAME} DESTINATION /usr/bin)
--- /dev/null
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <privacy_guard_client.h>
+#include <privacy_guard_client_internal.h>
+#include <time.h>
+
+#include "privacy_guard_dlp.h"
+#include "../ahocorasick/ahocorasick.h"
+#include "../ahocorasick/node.h"
+
+#define BRIGHTNESS 0
+#define RED 31
+#define GREEN 32
+#define YELLOW 33
+#define BG_BLACK 40
+
+static int fail_cnt = 0;
+static int success_cnt = 0;
+
+/* scenario settings */
+
+/** Test aho-corasick algorithm.
+ * Instructions: uncomment exactly ONE of the scenarios below. Set the number of target words (NWORDS).
+ * Adjust the other settings as required.
+ */
+
+/* only uncomment ONE of these at a time */
+#define SCENARIO_1 // pull words from text, parse same text
+//#define SCENARIO_2 // pull words from text, parse different text
+//#define SCENARIO_3 // pull words from text, parse random text
+//#define SCENARIO_4 // create random words, parse random text
+
+#define NWORDS 1000 // target number of words to search for
+
+#define WORD_SRCFILE "/tmp/smatch.txt"
+#define TEXT_SRCFILE "/tmp/smatch2.txt"
+
+#define SMATCH_BUFSIZE 65536 // text packet buffer size
+
+//#define SHOW_ADDED // uncomment to show strings as they are added
+#define DUMP_TREE // uncomment to dump the tree after adding strings
+//#define SHOW_MATCHES // uncomment to show details of each match
+
+///////////////////////////////////////////////////////////////////////////////
+// test utilities (aho-corasick)
+///////////////////////////////////////////////////////////////////////////////
+
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <fcntl.h>
+
+static int fastrand(int max)
+{
+ static int next = 0;
+ next = next * 1103515245 + 12345;
+ return ((unsigned)(next / 65536) % max);
+}
+
+static void __change_color_to_red(void)
+{
+ printf("%c[%d;%dm", 0x1B, BRIGHTNESS, RED);
+}
+
+static void __change_color_to_green(void)
+{
+ printf("%c[%d;%dm", 0x1B, BRIGHTNESS, GREEN);
+}
+
+static void __change_color_to_yellow(void)
+{
+ printf("%c[%d;%dm", 0x1B, BRIGHTNESS, YELLOW);
+}
+
+static void __change_color_to_origin(void)
+{
+ printf("%c[%dm", 0x1B, 0);
+}
+
+static void __start_test(const char *function_name)
+{
+ __change_color_to_yellow();
+ printf("================================================================================\n");
+ printf("\t%s\n", function_name);
+ printf("================================================================================\n");
+ __change_color_to_origin();
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// test verfication utility
+///////////////////////////////////////////////////////////////////////////////
+
+// Test String Match (ahocorasick)
+static void __test_string_match()
+{
+ __start_test(__FUNCTION__);
+ unsigned int i = 0;
+ unsigned long stime;
+
+ printf("Search match: ");
+
+ int awl = 0;
+ char buf[SMATCH_BUFSIZE];
+
+#ifndef SCENARIO_4
+ // load text from file
+ int fd = open(WORD_SRCFILE, O_RDONLY);
+ if (fd < 0) {
+ printf("Could not open " WORD_SRCFILE ". It should be a text file for me to find source words.\n");
+ return;
+ }
+ ssize_t tsize = read(fd, buf, SMATCH_BUFSIZE - 1);
+ if (tsize <= 0) {
+ printf("Could not read from " WORD_SRCFILE "\n");
+ close(fd);
+ return;
+ }
+ close(fd);
+ memset(buf + tsize, 0, 1);
+
+ // count words in text
+ int nwords = 1;
+
+ for (i = 0; i < tsize; i++) {
+ if (buf[i] == ' ') nwords++;
+ }
+#endif
+
+ int res = 0;
+ ac_instance *ac = ahocorasick_init();
+ struct timeval tv;
+
+ gettimeofday(&tv, NULL);
+ stime = tv.tv_sec * 1000000 + tv.tv_usec;
+
+ for (i = 1; i <= NWORDS; i++) {
+#ifdef SCENARIO_4
+ int j;
+ char *word = malloc(8);
+ for (j = 0; j < 7; j++) word[j] = (char)('a' + fastrand(20));
+ word[7] = 0;
+#else
+ // get a random number between 1 and nwords
+ int start = -1, j;
+ int idxword = fastrand(nwords - 1) + 1;
+
+ for (j = 0; idxword > 0; j++) {
+ if (idxword == 1 && start == -1) start = j;
+ if (buf[j] == ' ') idxword--;
+ }
+ if (j - start < 6) {
+ i--;
+ continue;
+ }
+
+ char *word = strndup(buf + start, j - start - 1);
+#endif
+ awl += strlen(word);
+ int nres = ahocorasick_add_string(ac, word, (void *)i);
+#ifdef SHOW_ADDED
+ printf("Added: .%s. %d\n", word, strlen(word));
+#endif
+ res = nres;
+ free(word);
+ }
+
+ awl = awl / i;
+
+ gettimeofday(&tv, NULL);
+ stime = tv.tv_sec * 1000000 + tv.tv_usec - stime;
+ printf("Build tree took %.2f msec for %d words (%d unique), average word len was %d\n", stime / 1000., NWORDS, res, awl);
+ stime = tv.tv_sec * 1000000 + tv.tv_usec;
+
+#ifdef SCENARIO_2
+ // load alternate text
+ fd = open(TEXT_SRCFILE, O_RDONLY);
+ if (fd < 0) {
+ printf("Could not open " TEXT_SRCFILE ". It should be a related text file for me to search for matches.\n");
+ return;
+ }
+ tsize = read(fd, buf, SMATCH_BUFSIZE - 1);
+ if (tsize <= 0) {
+ printf("Could not read from " TEXT_SRCFILE "\n");
+ return;
+ }
+ close(fd);
+ memset(buf + tsize, 0, 1);
+#endif
+
+#if defined SCENARIO_3 || defined SCENARIO_4
+ for (i = 0; i < 32768; i++)
+ buf[i] = (char)fastrand(100) + 30;
+ buf[32768] = 0;
+
+#endif
+ const char *text = buf;
+ ac_match *match;
+
+#ifdef DUMP_TREE
+ dump_tree(ac->root, stdout);
+#endif
+
+ ahocorasick_set_text(ac, text, strlen(text), 0);
+
+ res = 0;
+ do {
+ match = ahocorasick_find_next(ac);
+
+ if (match != NULL) {
+#ifdef SHOW_MATCHES
+ for (i = match->position; i < match->position + match->size; i++) printf("%c", text[i]);
+ printf("\n");
+ printf("got match for %p at %d len %d\n", match->user_data, match->position, match->size);
+#endif
+ res++;
+ }
+ } while (match != NULL);
+
+ gettimeofday(&tv, NULL);
+ stime = tv.tv_sec * 1000000 + tv.tv_usec - stime;
+ printf("Parsing took %.2f msec\n", stime / 1000.);
+
+ printf("Got a total of %d matches.\n", res);
+
+ ahocorasick_free(ac);
+}
+
+//////////////////////////////////////////////////////////////////////////
+// Main
+//////////////////////////////////////////////////////////////////////////
+int main()
+{
+ __change_color_to_green();
+ printf("DLP Test Start\n");
+ __change_color_to_origin();
+
+ /////////////////////////////////////////////////////////////////////////
+ // Test String Match (ahocorasick)
+ __test_string_match();
+
+ //////////////////////////////////////////////////////////////////////////
+
+ __change_color_to_green();
+
+ printf("Test Complete\n");
+ printf("success : %d, ", success_cnt);
+ __change_color_to_red();
+ printf("fail : %d\n", fail_cnt);
+ __change_color_to_origin();
+
+ return 0;
+}
static int success_cnt = 0;
static long interval[5000];
-typedef struct rec {
- char char_vec[32000];
-} RECORD;
-
// Packet to match 6 rules: Personal Document, Birth Date, Email, Address, Full Name and PhoneNumber
char packet_match_6rules[] = "GET /sync/pubmatic/csrc/7/44D1C4FE-60A-4 HTTP/1.1" \
"Host: pr-bh.ybp.yahoo.com" \