Recent

Author Topic: An advice - um conselho  (Read 6418 times)

ezlage

  • Guest
An advice - um conselho
« on: April 20, 2018, 10:19:12 pm »
Since 2010, when I signed up for this forum, I've been studying about and looking for a way to protect cryptographic keys inside executables or libraries. Along the way I learned that it is impossible to protect absolutely because keys are clean parameters for cryptographic functions and methods, so there will always be risks. From then on, my focus has become reducing the attack surface to a minimum, and I'm close to completing my task.

I created a component that I call AppShield. The functions of it add some things that the already known UniqueInstance, OnGuard, StrHolder and others do (not only them, not all of them). I preferred not to reuse the code of the referred ones to facilitate my understanding on the interaction of pieces of code and the operation as a single piece. I only extract the idea of ​​each one, since ideas are not subject to licensing or patents. However, most of my component is made up of functions and methods of encryption, compression, xor, key derivation, message authentication, hash/checksum, execution of protected SQL code (SQLite/SQLCipher pragmas key/rekey for example), prevention against SQL Injection, protection of strings and texts. The protections embrace the execution time, design time, distribution time and loading time.

Many here in the forum contributed to my work, I will thank them again later. I received very good suggestions, like using hardlocks/dongles. I implanted the suggestions that were possible for me, but hardlocks/dongles involve costs, so I could use this alternative only when my other projects, which demand this one, start to give me a financial return.

Although it has been eight years of my effort, I do not mind opening the code, but due to the impossibility of absolute protection, I fear that knowledge about the code will be a map to circumvent the mechanisms that would theoretically reduce the attack surface. So the big question is: release the code would increase or decrease the safety of my component?

Please convince me of something because I am very hesitant.


=== Now in Brazilian Portuguese ===

Desde 2010, quando me inscrevi neste fórum, venho estudando sobre e procurando por uma forma de proteger chaves criptográficas dentro de executáveis ou bibliotecas. No caminho aprendi que é impossível proteger absolutamente porque as chaves são parâmetros limpos para as funções e métodos de criptografia, então sempre haverá riscos. Daí em diante, meu foco se tornou reduzir a superfície de ataque ao mínimo, e estou próximo de concluir minha tarefa.

Criei um componente que denomino como AppShield. As funções dele agregam algumas coisas que os já conhecidos UniqueInstance, OnGuard, StrHolder e outros fazem (não apenas elas, nem todas elas). Preferi não reaproveitar o código dos referidos para facilitar o meu entendimento sobre a interação dos pedaçoes de código e o funcionamento como uma peça única. Extraí apenas a idéia de cada um, já que idéias não estão sujeitas a licenciamento ou patentes. Todavia, a maior parte do meu componente é composta por funções e métodos de criptografia, compressão, xor, derivação de chave, autenticação de mensagens, hash/checksum, execução de código SQL protegido (pragmas key/rekey do SQLite/SQLCipher por exemplo), prevenção contra SQL Injection, proteção de strings e textos. As proteções abragem o tempo de execução, tempo de design, tempo de distribuição e tempo de carregamento.

Muitos aqui do fórum contribuíram com o meu trabalho, eu irei adradecê-los novamente depois. Recebi sugestões muito boas, como utilizar hardlocks/dongles. Eu implantei as sugestões que eram possíveis pra mim, mas hardlocks/dongles envolvem custos, então eu poderia utilizar essa alternativa apenas quando meus outros projetos, quais demandam este, começarem a me dar retorno financeiro.

Embora tenham sido oito anos do meu esforço, não me importo em abrir o código, mas devido à impossibilidade de proteger de forma absoluta, temo que o conhecimento sobre o código venha a ser um mapa para contornar os mecanismos que teoricamente reduziriam a superficie de ataque. Então, a grande questão é: liberar o código fonte aumentaria ou diminuiria a segurança do meu componente?

Por favor, convençam-me de alguma coisa porque estou muito indeciso.
« Last Edit: April 20, 2018, 11:01:18 pm by ezlage »

hrayon

  • Full Member
  • ***
  • Posts: 116
Re: An advice - um conselho
« Reply #1 on: April 21, 2018, 01:58:27 am »
Hello! Another information to put on the scale. Imagine not releasing the code, just the binary part. And someone breaks your protection. Will you release a fix on your software? Another question: Consider whether your code is stolen and sold under another name. How effective will the application and monitoring of the license be? Are you prepared to accept that theft can occur and that others can make money from your work without crediting you?


Olá! Uma outra informação para colocar na balança. Imagine que não libere o código, apenas a parte binária. E que alguém quebre a sua proteção. Você liberará uma correção no seu software? Outra questão: avalie a possibilidade do seu código ser roubado e vendido sob outro nome. O quão efetiva será a aplicação e monitoramento da licença? Está preparado para aceitar que o roubo pode ocorrer e que outros poderão fazer dinheiro com seu trabalho sem creditá-lo?

Thaddy

  • Hero Member
  • *****
  • Posts: 14164
  • Probably until I exterminate Putin.
Re: An advice - um conselho
« Reply #2 on: April 21, 2018, 06:58:30 am »
Quote
Although it has been eight years of my effort, I do not mind opening the code, but due to the impossibility of absolute protection, I fear that knowledge about the code will be a map to circumvent the mechanisms that would theoretically reduce the attack surface. So the big question is: release the code would increase or decrease the safety of my component?

Please convince me of something because I am very hesitant.
https://en.wikipedia.org/wiki/Security_through_obscurity
IOW: such schemes are not really a good idea on their own. Real protection comes through legal means, like licenses, copyrights and  patents.
It protects only against the most simple minded naughty boys and girls, not against professionals. After all: if code can be executed its codepath *must* be known.
In practice there is no such thing as "theoretically reduce the attack surface". The theory - computer science - says the opposite: it is impossible to achieve.
The attack surface is not reduced.
The population that can attack may be slightly reduced for lack of knowledge or capablities but the attack surface itself is the same.
That also goes for e.g. using dongles. If one is available, you can reverse engineer it. Again: the codepath *must* be known otherwise your software doesn't work.
And that is not only the only correct theory, it is a fact....

See also https://en.wikipedia.org/wiki/Kerckhoffs%27s_principle
« Last Edit: April 21, 2018, 09:16:57 am by Thaddy »
Specialize a type, not a var.

dbannon

  • Hero Member
  • *****
  • Posts: 2778
    • tomboy-ng, a rewrite of the classic Tomboy
Re: An advice - um conselho
« Reply #3 on: April 21, 2018, 09:59:32 am »
I used to work for an organization that was considering purchasing some quite expensive systems, inc software, from IBM. I asked did they use copy protection and the engineer said, with a grin, "we prefer to spend spare money on good lawyers".

We purchased the system in question, were free to move that software around and were careful not to step over the spirit of the rules. And it was a good buy.

So, as well as the efficacy of your copy protection, please consider just how much your customers might grow to hate it !

(I do recognize that for many of us, IBM's lawyers and my past organizations profile do not apply...)

D

Lazarus 2, Linux (and reluctantly Win10, OSX)
My Project - https://github.com/tomboy-notes/tomboy-ng and my github - https://github.com/davidbannon

Thaddy

  • Hero Member
  • *****
  • Posts: 14164
  • Probably until I exterminate Putin.
Re: An advice - um conselho
« Reply #4 on: April 21, 2018, 01:09:31 pm »
Quote
"we prefer to spend spare money on good lawyers".
Quite so.
He may also want to read https://en.wikipedia.org/wiki/OllyDbg and subsequent links. (And try it... practicality!)
« Last Edit: April 21, 2018, 01:18:12 pm by Thaddy »
Specialize a type, not a var.

hrayon

  • Full Member
  • ***
  • Posts: 116
Re: An advice - um conselho
« Reply #5 on: April 21, 2018, 02:43:40 pm »
(Using Google Translator)
I work in a company that maintains a system with Firebird database. In one client, another service provider who took care of hardware maintenance stole the client's database and developed another system on the same database, making some cosmetic changes, and started offering it to my clients. Years of work to develop a consistent solution in the database have been stolen. The used version of Firebird allowed the copying of data with the database metadata - names and relationships between entities, triggers, stored procedures.
I discovered this by losing a customer and realizing that the new software vendor was also the one who took care of the hardware.
I think the ezlage solution might make it difficult to do this - not necessarily Firebird.
1) I could not have noticed, and lost more customers;
2) I just discovered that it was a copy of my company's work because for the termination of my contract it said that I would have unrestricted access to the server computer to export the data to the deployment of the other system. And if I could not, how would you gather evidence?
3) What is black and brown and matches with a lawyer? A Doberman. Not even in all cultures does the concept of justice stand above personal interests, including - and perhaps most importantly - those working for the law. By the way, Brazil. Here we are experts in creating bureaucracy to generate work and expenses, which may not fit in the pocket of a software developer.
---
Trabalho em uma empresa que mantém um sistema com banco de dados Firebird. Em um cliente, outro prestador de serviço que cuidava da manutenção do hardware roubou o banco de dados do cliente e desenvolveu outro sistema sobre o mesmo banco de dados, fazendo algumas alterações cosméticas, e começou a oferecer para meus clientes. Anos de trabalho para desenvolver uma solução consistente no banco de dados foram roubadas. A versão usada do firebird permitiu a cópia dos dados com os metadados do banco - nomes e relacionamentos entre as entidades, as triggers, as stored procedures.
Descobri isso ao perder um cliente e perceber que o novo fornecedor de software era o também quem cuidava do hardware.
Creio que a solução de ezlage poderá dificultar a ação desse tipo - não necessariamente do Firebird.
1)Eu poderia não ter percebido, e perdido mais clientes;
2)Eu apenas descobri que era uma cópia do trabalho da minha empresa pois para o término do meu contrato dizia que eu teria acesso irrestrito ao computador servidor para exportar os dados para a implantação do outro sistema. E se eu não pudesse, como juntaria provas?
3)O que é preto e marrom e combina com um advogado? Um doberman. Nem em todas as culturas o conceito de justiça está acima dos interesses pessoais, inclusive - e talvez principalmente - dos que trabalham para a lei. Diga-se de passagem, Brasil. Aqui somos experts em criar burocracia para gerar trabalho e despesas, o que pode não caber no bolso de um desenvolvedor de software.
« Last Edit: April 21, 2018, 03:09:00 pm by hrayon »

ezlage

  • Guest
Re: An advice - um conselho
« Reply #6 on: April 21, 2018, 10:16:30 pm »
Hello! Another information to put on the scale. Imagine not releasing the code, just the binary part. And someone breaks your protection. Will you release a fix on your software? Another question: Consider whether your code is stolen and sold under another name. How effective will the application and monitoring of the license be? Are you prepared to accept that theft can occur and that others can make money from your work without crediting you?


Olá! Uma outra informação para colocar na balança. Imagine que não libere o código, apenas a parte binária. E que alguém quebre a sua proteção. Você liberará uma correção no seu software? Outra questão: avalie a possibilidade do seu código ser roubado e vendido sob outro nome. O quão efetiva será a aplicação e monitoramento da licença? Está preparado para aceitar que o roubo pode ocorrer e que outros poderão fazer dinheiro com seu trabalho sem creditá-lo?

Hi, hrayon! Thanks for the answer.

The reason that led me to develop this component was another project, a software manager and financial organizer, tax and etc. So if I release the code then it's just the security component, not the projects that will make use of it.

If I release the code, I would put it in GitHub or similar service, where people could collaborate, report bugs and discuss. In this way, corrections, evolutions and adaptations would be made as needed.

In the specific case of this component, if the release of code happens, as it is only accessory of the products through which I want to obtain financial return, would be given the right to redistribute and resell. My goal is not to protect the program itself, but the program user data, which are encrypted. It's okay if someone gets the code, what I can not allow is someone to get the user's data. So I needed to develop a component that protected cryptographic keys, SQL commands, and so on.

=== In Brazilian Portuguese ===

Olá, hrayon! Obrigado pela resposta.

O motivo que me levou a desenvolver esse componente foi um outro projeto, de um software gerenciador e organizador financeiro, tributário e etc. Então, se houver liberação de código será apenas do componente de segurança, não dos projetos que farão uso dele.

Se eu liberar o código, colocaria no GitHub ou serviço similar, onde as pessoas poderiam colaborar, reportar bugs e discutir. Dessa forma, correções, evoluções e adaptações seriam feitas conforme a necessidade.

No caso específico deste componente, se a liberação de código vier a acontecer, como é apenas acessório dos produtos através dos quais pretendo obter retorno financeiro, seria dado o direito de redistribuir e revender. Meu objetivo não é proteger o programa em si, mas os dados do usuário do programa, que são criptografados. Tudo bem se alguém obtiver o código, o que não posso permitir é que alguém obtenha os dados do usuário. Por isso precisei fazer um componente que protegesse chaves criptográficas, comandos SQL e etc.

ezlage

  • Guest
Re: An advice - um conselho
« Reply #7 on: April 22, 2018, 09:05:04 pm »
Quote
Although it has been eight years of my effort, I do not mind opening the code, but due to the impossibility of absolute protection, I fear that knowledge about the code will be a map to circumvent the mechanisms that would theoretically reduce the attack surface. So the big question is: release the code would increase or decrease the safety of my component?

Please convince me of something because I am very hesitant.
https://en.wikipedia.org/wiki/Security_through_obscurity
IOW: such schemes are not really a good idea on their own. Real protection comes through legal means, like licenses, copyrights and  patents.
It protects only against the most simple minded naughty boys and girls, not against professionals. After all: if code can be executed its codepath *must* be known.
In practice there is no such thing as "theoretically reduce the attack surface". The theory - computer science - says the opposite: it is impossible to achieve.
The attack surface is not reduced.
The population that can attack may be slightly reduced for lack of knowledge or capablities but the attack surface itself is the same.
That also goes for e.g. using dongles. If one is available, you can reverse engineer it. Again: the codepath *must* be known otherwise your software doesn't work.
And that is not only the only correct theory, it is a fact....

See also https://en.wikipedia.org/wiki/Kerckhoffs%27s_principle

Hello Thaddy! I apologize for the delay.

I understand that obfuscating is not assuring, I believe you have already told me this before. I thank you again.

I am guided by the premise that while it is not possible to fully protect, I also can not leave SQL strings and cryptographic keys wide open in the application. Since it is necessary to use encryption, I will use several layers and never leave more than one key in clear text in memory, even then, in the fraction of a second it is used, once per execution. There will be another layer where the user must provide a key or counter key, and it can be used as a login. Once a key has been stolen from the component, there will still be others, it will not be known which sequence it was used in, nor with which ciphers, hashs and password derivation functions (type names and etc are changed after compilation). So when I say "reduce attack surface" I mean that data, passwords and strings that would be exposed all the time would be like this only in the thousandths of a second they were used, nevertheless, always one at a time.

Just remembering, as I told hrayon, the purpose is not to protect the application, its code or license, but the user data, which would be encrypted. The same goes for a future use of a dongle/hardlock. Taking advantage, I ask: Considering all this is not a good idea and does not reduce the attack surface, why Autodesk, Microsoft and so many others use dongles/hardlocks, protected string types and even fallible license controls?

The links you've sent have served me well, I'm reflecting on them. Thank you!

=== In Brazilian Portuguese ===

Olá Thaddy! Peço desculpas pela demora.

Eu compreendo que obfuscar não é assegurar, acredito que você mesmo já tenha me dito isso antes. Volto a agradecê-lo.

Me guio pela premissa de que, embora não seja possível proteger totalmente, também não posso deixar as strings SQL e chaves criptográficas escancaradas no aplicativo. Sendo necessário usar criptografia, utilizarei várias camadas e nunca deixarei mais de uma chave em texto limpo na memória, mesmo assim, na fração de segundo em que for utilizada, uma única vez por execução. Também haverá uma camada em que o usuário precisa fornecer uma chave ou contra-chave, sendo possível aproveitá-la como login/logon. Obtendo-se uma chave do componente, ainda haverá outras, não se saberá em qual sequência ela foi utilizada e nem com quais cifras, hashs e funções de derivação de senha (os nomes dos tipos e etc são alterados depois da compilação). Então, quando digo "reduzir a superfície de ataque" quero dizer que dados, senhas e strings que estariam o tempo todo expostos ficariam assim apenas no milésimo de segundo em que fossem utilizadas, mesmo assim, sempre uma por vez.

Apenas lembrando, como eu disse ao hrayon, o objetivo não é proteger o aplicativo, seu código ou licença, mas sim os dados do usuário, que estariam criptografados. O mesmo vale para um futuro uso que eu fizer de um dongle/hardlock. Aproveitando, pergunto: Considerando que tudo isso não é uma boa idéia e que não reduz a superfície de ataque, por quê Autodesk, Microsoft e tantas outras utilizam dongles/hardlocks, tipos protegidos de string e até mesmo falíveis controles de licença?

Os links que enviou me serviram bem, estou refletindo sobre eles. Obrigado!

ezlage

  • Guest
Re: An advice - um conselho
« Reply #8 on: April 22, 2018, 09:18:59 pm »
I used to work for an organization that was considering purchasing some quite expensive systems, inc software, from IBM. I asked did they use copy protection and the engineer said, with a grin, "we prefer to spend spare money on good lawyers".

We purchased the system in question, were free to move that software around and were careful not to step over the spirit of the rules. And it was a good buy.

So, as well as the efficacy of your copy protection, please consider just how much your customers might grow to hate it !

(I do recognize that for many of us, IBM's lawyers and my past organizations profile do not apply...)

D

Hello dbannon!

I like your example. However, as I just told Thaddy, I intend to protect user data, not the program. And everything transparently, so customers would not hate me for it. Not for this reason, I guess.

Thank you.

=== In Brazilian Portuguese ===

Olá dbannon!

Gostei do seu exemplo. Porém, como acabei de dizer para o Thaddy, pretendo proteger os dados do usuário, não o programa. E tudo de forma transparente, portanto, os clientes não me odiariam por isso. Não por esse motivo, acredito.

Muito obrigado.

ezlage

  • Guest
Re: An advice - um conselho
« Reply #9 on: April 22, 2018, 10:11:52 pm »
Quote
"we prefer to spend spare money on good lawyers".
Quite so.
He may also want to read https://en.wikipedia.org/wiki/OllyDbg and subsequent links. (And try it... practicality!)

If I had money, spending it could solve the problem. But I have none. So I need to try to get around.

Thanks again, Thaddy. I will try to practice through OllyDbg.

=== PT-BR ===

Se eu tivesse dinheiro, gastá-lo poderia resolver o problema. Mas não tenho nenhum. Então preciso tentar contornar.

Obrigado novamente, Thaddy. Tentarei praticar através do OllyDbg.

hrayon

  • Full Member
  • ***
  • Posts: 116
Re: An advice - um conselho
« Reply #10 on: April 23, 2018, 01:27:11 pm »
Hello!
So, the ideal is to get the answer from those who break codes.
Ever tried asking in a hacker forum?
I do not program at such a low level but I imagine that if you provide the protection code that will be compiled with each program, not necessarily breaking a program will make all the different programs that use the same protection easily breakable, from this point of view: with your code available, each one can make customizations that change the behavior of the part you have programmed, but there is a possible problem here ...
Depending on the license of your software, each customization can be made public if requested, which would make the customizations relatively "weak" for security.

---

Olá!
Então, o ideal é obter a resposta de quem costuma quebrar códigos.
Já experimentou perguntar num fórum de hackers?
Eu não programo em tão baixo nível, mas imagino que se disponibilizar o código de proteção que será compilado com cada programa, não necessariamente quebrar um programa tornará todos os diferentes programas que usam a mesma proteção facilmente quebráveis, ou ainda, quebráveis de forma sistematizada, sob esse ponto de vista: com o seu código disponível, cada um pode fazer customizações que mudem o comportamento da parte que programou, mas há um possível problema aqui...
Dependendo da licença do seu software, cada customização poderá ser tornada pública se requisitada, o que tornaria as customizações relativamente "fracas" para a segurança.

ezlage

  • Guest
Re: An advice - um conselho
« Reply #11 on: April 24, 2018, 11:47:05 am »
Hello!
So, the ideal is to get the answer from those who break codes.
Ever tried asking in a hacker forum?
I do not program at such a low level but I imagine that if you provide the protection code that will be compiled with each program, not necessarily breaking a program will make all the different programs that use the same protection easily breakable, from this point of view: with your code available, each one can make customizations that change the behavior of the part you have programmed, but there is a possible problem here ...
Depending on the license of your software, each customization can be made public if requested, which would make the customizations relatively "weak" for security.

---

Olá!
Então, o ideal é obter a resposta de quem costuma quebrar códigos.
Já experimentou perguntar num fórum de hackers?
Eu não programo em tão baixo nível, mas imagino que se disponibilizar o código de proteção que será compilado com cada programa, não necessariamente quebrar um programa tornará todos os diferentes programas que usam a mesma proteção facilmente quebráveis, ou ainda, quebráveis de forma sistematizada, sob esse ponto de vista: com o seu código disponível, cada um pode fazer customizações que mudem o comportamento da parte que programou, mas há um possível problema aqui...
Dependendo da licença do seu software, cada customização poderá ser tornada pública se requisitada, o que tornaria as customizações relativamente "fracas" para a segurança.

Thank you, hrayon.

I will look for people with a more specific knowledge, such as disassembly, cracking and etc. Meanwhile, as I've come this far, I'm going to study debuggers, assembly and what else is related. When I started this project I did not know anything about Lazarus, Freepascal or even Pascal/ObjectPascal, I think it's time to go deeper.

=== PT-BR ===

Obrigado, hrayon.

Vou procurar pessoas com um conhecimento mais específico, como desmontagem, cracking e etc. Enquanto isso, como já cheguei até aqui, vou estudar depuradores, montagem e o que mais estiver relacionado. Quando comecei esse projeto eu nada sabia sobre Lazarus, Freepascal ou mesmo Pascal/ObjectPascal, creio que já é hora de aprofundar mais.

ezlage

  • Guest
Re: An advice - um conselho
« Reply #12 on: April 24, 2018, 11:50:24 am »
I've been reflecting on what Thaddy said. I think I'd better think from his perspective, because if the unexpected happens, at least I will not be taken by surprise.

=== PT-BR ===

Estive refletindo sobre o que Thaddy disse. Acredito que seja melhor pensar da perspectiva dele, pois se o inesperado acontecer, pelo menos não serei pego de surpresa.

Thaddy

  • Hero Member
  • *****
  • Posts: 14164
  • Probably until I exterminate Putin.
Re: An advice - um conselho
« Reply #13 on: April 24, 2018, 01:01:55 pm »
Note I also wrote on their own. It may help, but not against determined hackers. It is a matter of value: how valuable is the software for how many people?
I see you have tried OllyDbg  :o  Then you know you are up against some really potent possible threats.  O:-)
So always search for a balance. But the balance is - in a corporate setting - always in favor of proper licensing.
Btw. Marcov has some experience along these lines too. He may want to add to or correct me.
« Last Edit: April 24, 2018, 01:04:23 pm by Thaddy »
Specialize a type, not a var.

ezlage

  • Guest
Re: An advice - um conselho
« Reply #14 on: August 23, 2018, 10:51:34 pm »
Friends,

A few days ago I made my decision and began to make everything available. I registered with GitHub (https://github.com/ezlage) and created a repository (https://github.com/ezlage/sempercom). I've pushed a few things, but the flagship (TAppShield) will be pushed out soon.

I thank everyone.

=== PT-BR ===

Amigos,

Há alguns dias tomei minha decisão e comecei a disponibilizar tudo. Fiz um cadastro no GitHub (https://github.com/ezlage) e criei um repositório (https://github.com/ezlage/sempercom). Já empurrei algumas coisas, mas o carro chefe (TAppShield) será empurrado em breve.

Agradeço a todos.

 

TinyPortal © 2005-2018