ASecuritySite Podcast

ASecuritySite Podcast

By Professor Bill Buchanan OBEScienceTechnology
Download on the App Store

ASecuritySite Podcast episodes

  • Bill Buchanan - Lesson 1 in Secure Programming: Don't Reuse Your IVs

    Blog: https://medium.com/asecuritysite-when-bob-met-alice/lesson-1-in-secure-programming-dont-reuse-your-ivs-5666ddfa9a1c

    I wrote up an article on a recent Samsung vulnerability [here], and one comment said … "it's an old bug, reuse of IV (Initialisation Vectors) seem a very basic problem". On the face of it, the comment perhaps doesn't go into enough detail, so I'll try and explain the "bug" and hopefully show that it is shockingly bad coding … almost negligent in terms of protection, and could even be seen as an intentional backdoor.

    And for a "very basic problem", it should perhaps be "extremely bad coding", and this "bug" should never, ever be seen within trusted environments. It shows an almost complete lack of knowledge in how cryptography works, with a novice vulnerability. The paper is here [1]:

    In fact, it's like WEP all over again, and where the WEP Wifi method had a small IV (Initialisation Vector), and when it rolled out, it was possible to just XOR cipher streams, and discover the plaintext. The asleep program could crack any Cisco access point in less than a day. Luckily we now use WPA-2, and which does not have the reuse of the IV.

    I hope to show that we should be worried if code such as this ever gets near a user's device. In fact, if there was ever a back door in a mobile phone, it could be this one.

    If you want to read about the "bug", try here:

    Crypto Bug in Samsung Galaxy Devices: Breaking Trusted Execution Environments (TEEs) If you use an Apple Macbook, it's likely that you have a secret enclave for important secrets — such as your encryption…

    medium.com

    A bad "bug"

    Now, I will explain how bad this "bug" is. If you are into cybersecurity, you should hopefully know that AES GCM is a stream cipher. With this, we take a secret key value and a salt value (an IV — Initialisation Vector) and generate a pseudo infinite keystream. Our plaintext is then simply XOR-ed with the keystream to produce our ciphertext:

    The salt value should then always be random, as a fixed salt value will always produce the same keystream for the same plaintext, and where we can reveal the keystream by XOR-ing cipher streams, and eventually revealing the plaintext. In the case of the key wrapping, the plaintext is an encryption key, and thus the encryption key used by the TEE will be revealed.

    If we reuse IVs, Eve will be able to XOR cipher streams together and reveal the keystream (K). From there she can decrypt every cipher stream, but simply XOR-ing the cipher stream with K.

    Coding

    AES GCM (Galois Counter Mode) is a stream cipher mode for AES. It is based on the CTR mode but converts to a stream cipher. This provides low latency in the encryption/decryption process and is fast to process. Along with this, it integrates AEAD mode for authentication. But as GCM is a stream cipher mode, it is open to a reuse IV attack. With this, the IV (Initialization Vector) of the cipher is the same for two cipher messages. We can then XOR to the two cipher streams together to reveal the cipher stream key (K). We can then reveal the plaintext by XOR-ing any cipher stream with K.

    So, let's try some code to do this. In this case, I will use Golang to show the basic principles of the method. I will use a static key in this case (as this would not change within the TEE) of "0123456789ABCDEF" (16 bytes — 128-bit key), and a static nonce of "0123456789AB" (12 bytes — 96 bits) [here]:

    package mainimport ( "crypto/aes" "crypto/cipher" "fmt" "os")func xor(a, b []byte, length int) []byte { c := make([]byte, len(a)) for i := 0; i c[i] = a[i] ^ b[i] } return (c)}func main() { nonce := []byte("0123456789AB") key := []byte("0123456789ABCDEF") block, err := aes.NewCipher(key) if err != nil { panic(err.Error()) } msg1 := "hello" msg2 := "Hello" argCount := len(os.Args[1:]) if argCount > 0 { msg1 = (os.Args[1]) } if argCount > 1 { msg2 = (os.Args[2]) } plaintext1 := []byte(msg1) plaintext2 := []byte(msg2) aesgcm, err := cipher.NewGCM(block) if err != nil { panic(err.Error()) } ciphertext1 := aesgcm.Seal(nil, nonce, plaintext1, nil) ciphertext2 := aesgcm.Seal(nil, nonce, plaintext2, nil) xor_length := len(ciphertext1) if len(ciphertext1) > len(ciphertext2) { xor_length = len(ciphertext2) } ciphertext_res := xor(ciphertext1, ciphertext2, xor_length) fmt.Printf("Message 1:\t%s\n", msg1) fmt.Printf("Message 2:\t%s\n", msg2) fmt.Printf("Cipher 1:\t%x\n", ciphertext1) fmt.Printf("Cipher 2:\t%x\n", ciphertext2) fmt.Printf("Key:\t\t%x\n", key) fmt.Printf("Nonce:\t\t%x\n", nonce) fmt.Printf("XOR:\t\t%x\n", ciphertext_res) plain1, _ := aesgcm.Open(nil, nonce, ciphertext1, nil) plain2, _ := aesgcm.Open(nil, nonce, ciphertext2, nil) fmt.Printf("Decrypted:\t%s\n", plain1) fmt.Printf("Decrypted:\t%s\n", plain2)}

    When we run with "hello" and "Hello" we get [here]:

    Message 1: helloMessage 2: HelloCipher 1: 7fcbe7378c2b87a5dfb2803d4fcaca8d5cde86dbfaCipher 2: 5fcbe7378cf8c68b82a2b8d705354e8d6c0502cef2Key: 30313233343536373839414243444546Nonce: 303132333435363738394142XOR: 2000000000d3412e5d1038ea4aff840030db841508Decrypted: helloDecrypted: Hello

    If we try "hello" and "Cello", we can see that there's a variation in the first byte of the cipher stream:

    Message 1: helloMessage 2: CelloCipher 1: 7fcbe7378c2b87a5dfb2803d4fcaca8d5cde86dbfaCipher 2: 54cbe7378c5638db82df34a46172abed62b887aa48Key: 30313233343536373839414243444546Nonce: 303132333435363738394142XOR: 2b000000007dbf7e5d6db4992eb861603e660171b2Decrypted: helloDecrypted: Cello

    The "bug" allowed a user program to request their own IV, which meant that a cracker would continually request the same IV, and then break the cipher, and reveal the encryption key used. This is because the TEE (Trusted Execution Environment) uses key wrapping to encrypt the encryption key with AES GCM, so a cracker can request these wrapped keys, but with their own IV. This then reveals the key that the TEE is using. This is extremely bad coding!

    Conclusion

    This is extremely bad coding, and I would not expect this level of implementation from a new graduate. If a development team creating code within a TEE doesn't understand a reuse IV attack, they need to go on a secure coding training course before they ever touch any more trusted code. If this was an intentional backdoor, that's a whole other story. I hope, it was just a bug, but we really need to improve our knowledge in the creation of TEEs, as these also run within Cloud-based systems.

    Reference

    [1] Shakevsky, A., Ronen, E., & Wool, A. (2022). Trust Dies in Darkness: Shedding Light on Samsung's TrustZone Keymaster Design. Cryptology ePrint Archive.

    7 min
  • Bill Buchanan - The Art of the Backdoor

    Blog: https://medium.com/asecuritysite-when-bob-met-alice/the-art-of-the-backdoor-e39f001ea8b9

    Do you ever worry that your locksmith may take a copy of your key when they fit a new lock? Or that your locksmith has defined a lock which they know they have a skeleton key for? Or that your locksmith modifies the lock so that they can compromise it?

    And so we trust those that create locks to design them so that they cannot be broken easily, and that lock standard agencies around the world to set standards that promote good lock design, and, most of all, that locksmiths can be trusted to fit them without compromising them (and in giving us good advice).

    Introduction

    Well, let's look at software backdoors. Overall it's not an easy thing to put in a backdoor in a piece of software. Well, let me re-phrase that … "it is not an easy thing to put in a backdoor in a piece of software and for it not to be seen".

    Computer security is a serious business, but you must smile a little when you see the lengths that some intruders will go to in order to compromise systems. Organisations such as the NSA have long been accused of applying backdoors into cryptography software, but the recent Apple login hack shows that there are lots of opportunities for others to get in on the act. The addition of a backdoor in the Apple compiler showcased the opportunity for large-scale compromises.

    Overall there are a number of ways that a backdoor can be added to a piece of software:

    • Escrow. In encrypted communications, one method is to keep of copy of the encryption key that could be used at some time in the future. Details [here].
    • Defining a standard that you know you can crack. The NSA and law enforcement agencies around the world have been accused of helping to define a standard and setting various parameters, and they know they have the methods to crack them.
    • Source code addition backdoor. This is the typical way that an intruder would add a backdoor, and where the additional code is added which will perform a task that allows the source code writer back into the system. Normally the code is added by the writer, but then an intruder finds out the backdoor and can exploit it.
    • Injected code backdoor. With these, packages such as Metasploit insert some additional code into the application, which allows it to work the same, but creates a backdoor connection. Normally this is a call-out method, where the program calls out to the malware writer.
    • Compiler backdoor. This is the best method for going undetected, and where the compiler, itself, adds the additional code to every program which uses the compiler. In terms of a mass exploit, the compiler backdoor will have the greatest scope as it will exploit a wide range of applications. The executable will also be signed to verify that it is a valid application.
    • Vulnerability and XSS exploit. This involves compromising a system in order to create a backdoor, typically injecting code into a running application which causes the system to open up a backdoor connection.

    The open-up of a network connection will obviously be detected on the system, but code writers have implemented a number of smart ways to cover this up, including passing secret passphrases for passwords, or with port knocking, where network packets are sent to a well-known open port, which then causes another port to open.

    A. Defining a standard you know you can crack

    A key focus for law enforcement is the cracking of cryptography, especially for tunnels and VPN connections. Devices created by Juniper were found to have a flaw which allows agencies to decrypt VPNs traffic. The company may have also used Dual EC (Elliptic Curve) DRBG (Deterministic Random Bit Generator) for generating the random numbers required to create VPN tunnels. This method, which was promoted by the NSA, has a known weakness and can be cracked.

    The possible backdoor in Dual EC DRBG has been known about since 2004, and the team who worked on it had the chance to plug the gap but failed too. It thus allows law enforcement agencies to crack SSL/TLS encrypted traffic which used the method for random number generation. It was thus assumed that no one would use the method, but, in Juniper's case, it has been found in some of their devices.

    In 2013, Edward Snowden showed NSA memos which indicated that the NSA had been the sole editor of the standard, whereas NIST responded that it did not deliberately weaken any cryptography standard. The following year, NIST recommended that companies stop using it, and withdrew it from its draft guidance on random number generation. In 2013, also, OpenSSL was found to be implementing the method, which allowed TLS/SSL connections to be decrypted.

    The back door in the standard for Elliptic Curve method for Dual_EC_DRBY caused a great deal of suspicion on the definition of NIST's P curve standards, and that they had selected them so they could have an advantage in breaking the public keys. Most of the industry has moved away from the P standards (such as P-256) and towards Curve25519 (which is shown in the graphic on the right-hand side and which was created by Daniel J Bernstein), and now used by Tor, Signal, What's App, Facebook, OpenSSH, and many other standards. In 2013, Bruce Scheiner stated that he didn't trust the values selected:

    I no longer trust the constants. I believe the NSA has manipulated them through their relationships with industry

    I have plotted some of the standard Elliptic Curve parameters [here].

    B. Source code additional back door

    It has long been the case where code writers have added additional code which allows them back into the code whenever required. They will often add debug functions which can be remotely enabled, but where they forget to switch-off. This backdoor method works well until the source code is read, and the additional code is revealed. With the rise of Git hub repositories, it can become obvious as to when the backdoor has been added. The following outlines a few backdoors:

    A classic backdoor was added to an FTP server (vsftp), which has an intentional backdoor within the version running on it. The back door is exploited with the username ending with:

    ":)"

    and then the server listens on port 6200 and awaits a connection:

    root@ubuntu:~# telnet 1.2.3.4 21Trying https://www.linkedin.com/redir/invalid-link-page?url=192%2e168%2e99%2e131...Connected to https://www.linkedin.com/redir/invalid-link-page?url=10%2e200%2e0%2e1.Escape character is '^]'.220 (vsFTPd 2.3.4)user mybackdoor:)331 Please specify the password.pass none ^]telnet> quitConnection closed.telnet 1.2.3.4 6200Trying https://www.linkedin.com/redir/invalid-link-page?url=10%2e200%2e0%2e1...Connected to https://www.linkedin.com/redir/invalid-link-page?url=10%2e200%2e0%2e1.Escape character is '^]'.id;uid=0(root) gid=0(root)

    The UnrealRCD IRC daemon runs on port 6667. The version on Metasploitable has a backdoor where the user sends "AB", and then follows it with a system command on a listening port (see demo above).

    Intentional backdoors

    Cryptography cracking is often one of the most challenging areas for investigators to crack, so there have been many allegations of companies tampering with source code in order to create backdoors. While these are not necessarily network connections, the software is modified in a way which changes the functionality of the encryption function.

    One company — Crypto AG, a Swiss cryptography company who make encryption machines — has been accused of modifying their software in collusion with intelligence agencies from Germany (BND), the UK (GCHQ) and US (NSA). This was highlighted, in 1986, when Ronald Regan announced that the US had intercepted encrypted diplomatic communications between Tripoli and the Libyan embassy in East Berlin, related to a bombing in Berlin. In 1992, the Iranian government even arrested Hans Buehler, a salesman for the company, but was released in 1993 without revealing any flaws in the machines (and after $1 million bail money was paid).

    Crypto AG soon after dismissed Hans and requested he pay back the $1m. Since then Der Spiegel has interviewed former employees and concluded that the machine was indeed rigged. Even after several other investigations, there is still no conclusive proof of the rigging, but some suspect that the relationship with defence agencies goes back to 1954.

    Juniper backdoor

    Juniper recently announced that there were two backdoors on their devices, and which allowed intruders to gain administrator access and also decrypt the encrypted content. It was the kind of shock that has not been seen since the asleep script was released, and which could crack most Cisco Wi-fi access points which used the LEAP authentication method.

    With backdoors in cryptography being a hot topic, Juniper revealed that it had traced "unauthorized" code within its ScreenOS operating system on some of its firewalls, and which allowed an intruder to take complete control of Juniper's NetScreen firewalls using a hard-wired password. This would allow them to decrypt all the encrypted traffic for VPN connections. There is a patch for this, but intruders can now determine the required password — which has been hard-wired into the code — by examining the ARM code used in the backdoor:

    The strange thing is that the password is " password = "let a = b + 1"

    The following is a sample login:

    $ ssh [email protected]:

    Analysts have already managed to identify the password in just six hours. Overall the logs would just show that there was a successful login with "system":

    In 2013, Der Spiegel outlined the FEEDTHROUGH method which maintained a backdoor onto Juniper firewalls. This approach was different to the methods outlined in the latest backdoors, as it was a post-compromise.

    C. Injected code backdoor

    With this packages such as Metasploit insert some additional code into the application, and which allows it to work the same, but creates a backdoor connection. Normally this is a call-out method, where the program calls-out to the malware writer. The following shows the addition of call-back code into the Putty.exe application:

    This method is normally detected by virus scanners as it often adds a standard piece of code which can be detected on a system. When downloading standard programs, it is often important to take the hash signature of the application, in order to determine if it had been modified.

    D. Vulnerability and XSS exploit

    With a vulnerability exploit, the code writer has allowed the exploit to propagate through the system and cause it to open up a backdoor. This typically involves an XSS (Cross-site script), where some code is injected into running software and which propagates through the system to open up a network connection. Adobe Flash is a major contender here for this type of exploit where some shellcode is fed through the Flash plug-in and onto the system. There are many examples of where Flash has been compromised, in order to feed the code through, as it is typically running with high levels of trust in the system.

    E. Compiler injection backdoor

    In 1984, Ken Thompson, inventor of Unix, outlined how he could be injected a virus into a compiler. For this, he added the code into the code being compiled, and also into the compiler itself, so that the malware could be sustained in future versions of the compiler. He thus knew how to inject the malicious code into the compiler, but not leave a trace in the source code. As it was compiled into the lowest level of the code, it is almost impossible to detect the added code, as the source code shows no sign of the added code. While 1984 was the year of the release of the Apple Mac, it is Apple who was one of the first to be pinpointed by the methods that Ken outlined in the same year.

    Background

    A compiler converts high-level code, such as C++ or Pascal, into a machine ready equivalent (machine code). This can either be done to produce a portable executable, such as an EXE in Microsoft Windows. One way to compromise an application is to create a backdoor in the compiler so that a line of code such as:

    Console.WriteLine("Hello")

    could be compiled to perform the machine code equivalent of:

    Console.WriteLine("Hello")TcpSocket(9999);

    which might open up a network port (9999) which could be connected to. In this way when the app was uploaded onto a site, it would look as it was a valid compile. It thus means that good applications will be infected in the same way as bad apps, and will be signed by a trusted certificate.

    XcodeGhost

    WithXcodeGhost the target was Apple iOS, and which replaces Apple's Xcode (which is used to create iOS and Mac OS apps). Unfortunately, it is rather large to download (over 3GB), so in countries such as China, developers have had to download Xcode from untrusted sources, which had a backdoor added to it. This resulted in over 300 back-doored apps being added to the Apple App Store, including WeChat which is a messaging app used by over 600 million people.

    The malware itself is able to show phishing pages which are used to steal user credentials, and it does seem surprising that Apple allowed more than three dozen backdoored apps to be hosted on the App Store, including WeChat, Didi Kuaidi (a similar app to Uber for car-hailing), and NetEase Inc (a Spotify-like music app).

    Normally a program is produced and then signed with the private key of the developer, which verifies that it has come from a trusted source (a public key then verifies that the code has come from a trusted source and also that it has not been modified — known as code signing with a strong key). So, in the case of XcodeGhost, valid developers will produce signed apps but where they have a backdoor added in the executable program.

    Conclusion

    So we now see one of the first examples of a compiler backdoor. Backdoors will not go away, and if anything they will increase, as they are the natural way of someone silently compromising a system. The debate about backdoors in cryptography is now one of the most fundamental of the 21st Century, and it will not go ahead any time soon. With many countries looking to ban anonymous VPN access, the tension between security and privacy is just going to grow larger.

    20 min
  • Bill Buchanan - My Bluffer's Guide to Spin-out Success

    I often get asked about what makes a successful university spin-out, so here are my observation for any budding academic team looking to spin out:

    1. You need a solid academic base. A PhD programme is often an excellent base for a spin-out, as it involves three or more years of extensive study into every aspect of a given field. This involves both a macro and micro viewpoint of a problem, and it develops the skills that support the articulation of new knowledge and new discoveries. A great team, too, often has a foundation of both theory and practice.
    2. You need vision. Any company can innovate but fail to take things forward. A great team needs a visionary leader and who knows how to take something to the place which achieves this vision. They are a creator of a seed that is likely to sustain the company into its future.
    3. Build a team, focus on quality and keep them. I know it sounds obvious, but it's not easy to build a team in academia. There are too many barriers and academic structures that get in the way of team building. Try and create a team with complementary skills, and don't just build with a single focus on one skill. You need testers, coders, cloud scalers, documenters, presenters, and many other things. Try to always focus on the quality of your work and not quantity. Quality gets recognised, but quantity often does not. Anyone can produce a 100 research papers, but it takes a great team to produce a single groundbreaking paper.
    4. Get the right leader for the right stage. There are different types of leaders. Those who people respect for their technical expertise, those who understand how to make their offering to the market, and others who can scale a company. Get the right leader for the right stage — as they are often different people. Without a visionary, you will not need the next two leaders.
    5. Protect your IP. I know many dislike patents, but it's a dog-eat-dog world of innovation, and if you fail to protect your IP, others will come along and "borrow" from it or even "steal" it. Get a patent, if possible — not to attack others, but to defend yourself. The last thing you want is to licence your own invention from others.
    6. Abstract your ideas. While words are great, pictures and abstractions are so much better. Draw your ideas and concepts in a way that engages others.
    7. Research papers can be good. The importance of having peer review for any contribution to knowledge cannot be underlined enough, but, know that you have some IP protection in place and that you are further along the route than others in the development of your innovation. If your company wants to be a leader in its field, it needs to show that it has a strong scientific and technical base. And articulating complex thoughts in a research paper is a great way of showing that you have a core understanding of a field.
    8. Have a log book. I know this sounds trivial, but I have seen the difficult side of managing IP — when something becomes successful. It does no good in the future to say that you invented something when you have no real evidence. So, keep a log book and write down your thoughts as you develop your research, and get it signed by a trusted person (and with a date). I am still a fan of hardback log books and love it when a PhD student takes one along to meetings and jots down ideas.
    9. You need industry. A great invention will go nowhere without it being built at a production levels, and which matches to problems in the market. As early on, try to get industry involved, and focus the work.
    10. Build a team with theory and practice. Do not have one without the other. A great research team has the knowledge to ground the work in academic practice, but it needs practical skills to implement it.
    11. The leader is not the boss. The leader is not a role. The leader is whoever is sustaining the work.
    12. Research grants are a vehicle to sustain your vision. Unfortunately, many academics see research grants as isolated projects which must be implemented and delivered. They are routes to career advancement, and where they can tot-up their total grant income and display it as a KPI. But, are also stepping stones to your true innovation — each grant sustains the work and the team but takes you forward one little bit.
    13. Investors invest in people and not just innovation. Like it or not, investors are typically not investing in the great new invention but in the team that will take it forward. In most cases, this involves a break between the academic research and the spin-out.
    14. Four slide rule, always. You only need four slides: the problem, you and your team, your innovation, and how you will execute. Don't bore your audience; inspire them into your dream and vision, and listen to what they say. And, remember, it has a great simple opening slide — so dwell there as you introduce yourself and your vision. And end with a bang!
    15. Define the culture at an early stage. This might not seem to be a core focus, but it is important to lay out the ethics and morals of the company and how it will share any success that it gains. Those who invest their time and energy at an early stage should see rewards, and where no one is seen to have more than the share they deserve.
    16. Pick the right place and the right people. Don't grow your company in a place where you cannot attract the best talent. Pick a great city, and place yourself there.
    17. Get an amazing HR team in place. This is fundamental. Great companies are created by great people. Your recruitment should focus on those who focus on quality. They are people with an eye for detail but who can abstract things and who are able to focus on things. They are basically people who care more about responsibilities than their job titles. Recruit people for their talents and passion, and not because they have years of experience in given technologies. For example, it is often better to take an engineer or mathematician and train them in coding than to take a computer scientist and train them in engineering.
    18. Remove bureaucracy and rigid structures. Committees, bureaucracy and rigid structures often stifle innovation and allow some people to hide from their responsibilities. Rigid structures stop people from working across departmental boundaries, so try and be flexible — and allow a cross-fertilisation of ideas.
    19. No hiding place. There should be no place to hide a small and growing company. Those who fail to match up to the pace of the company and its vision should be allowed to leave. But, for those who do, the company should do as much as it can to retain them. Don't let any good employee leave without trying your best to keep them. Know why people want to leave, and try and address these things at an early stage.
    20. You need a common goal and purpose. A core part of a great team is that they have a core goal and purpose and where everyone shares this. A company must recruit for these purposes and find those who match them. A bad hire is a wasted opportunity and will only cost more money in the future. See №17.
    21. Praise those who are successful. A great team celebrates the success of their members and does not see it as a threat to themselves. Don't hide success in whatever form it appears.

    And finally:

    Success leads to more trust. When you write a research proposal, you have a long statement about why you should be trusted to gain the funds. A core part of this is defining and articulating your success. No one ever really defines all their failures, but for anyone who has been successful, this is probably been a core part of the reason they have been successful. So the more success you have, the more likely that you will be trusted with other people's money and time. If you cannot articulate your success to others, you will often struggle to influence others. Document and capture your successes are you go along, and get others to make comments on them.

    12 min
  • Bill Buchanan - Just Git ... and Smashing Windows

    There's one little program that I could not do my work without … Git.

    And, so, our digital world needs to say a great thanks to the wonderful Linus Torvalds. In fact, without him, our digital world would be a whole lot more locked-down and controlled by large and faceless companies. Without Linus, we would probably now be dominated by Microsoft Windows, and your car and your mobile phone would probably be running Windows for its interface (yuk!). And if the software in your car crashed — as it would likely do on a regular basis — you might possibly have to connect a keyboard to your instrument panel and press Ctrl-Alt-Del.

    Your TV, too, would possibly boot up into Microsoft Windows, and you'd need a mouse to control it. And our world of servers would possibly mainly be running on Microsoft IIS and use MS SQL databases. And, to back up your code, you would need a licence for Microsoft Backup 3.1, and where you dragged your folders over to make updates. Possibly, the command line terminal would have been dropped in favour of GUI (Graphical User Interface) approaches.

    So, just as in the famous advert from Apple in 1984 which illustrated the smashing of a Big Brother screen, Linus smashed the world of Windows — sorry for the pun!

    https://www.youtube.com/watch?v=2zfqw8nhUwA

    And, so rather than a world of Microsoft Windows, our world is full of Linux and associated distributions. For this, he wrote the first version of the Linux kernel and wrote the original version of Linux with pure machine code. I suppose there is something in the DNA for the Finnish people, that wants to be open about things, and not close them down with patents and restrictions.

    Git

    So, while the creation of Linux is possibly one of the greatest advancements in Computer Science. There is something even better … Git. With Git we have a version control system of code and documents. I use it every day, and it saves me so much time and effort. I use it in so many ways, including archiving my code and updating my Golang libraries. At its core is a smart way of keeping track of any version of a file and the difference between them.

    Linus wrote Git in 2005 for his Linux kernel but is now maintained by Junio Hamano. At its core, each host maintains a complete repository of all the files it has archived and how they have been modified. This differs from the client-server-based approach of code repositories, as the tracking can be done independently from a server.

    With Git, you end up with some commands that are hard-wired into your memory. We use "git add ." to add new files, then "git commit -m 'New update'" to search for changes in the files, and then finally a "git push" to upload the new versions. Then a "git pull" to get things back. Anyone who has ever lost their code or created a bad version will know the power of using Git to recover things. Three basic commands are thus:

    git add .git commit -m "My new update"git push

    But, it's not just code it can archive; it can archive many different document types, and it particularly likes mark-up documents such as LaTeX. Overall, Microsoft Word is terrible for version control, as the file is encapsulated in a Zip file. Many developers thus use LaTex and archive with Git. The great advantage of this is — just like Wiki's — we can trace the updates through text. It also allows us to easily share documents and allow collaborative work (as Git can keep a track of the update). And, for large files which are more than GBs in size there is Git Large File Storage (LFS) — git-lfs.

    And, so, if we were to start the Internet again, possibly LaTeX and Git would be used to create our documents, and we would have no Microsoft Word. In fact, we would probably not need Microsoft Windows, as our world would be open-sourced with the use of Linux. While Linux has always struggled to compete with Microsoft Windows and Mac OSX, it is open and free. The code for Linux, too, is open to all to examine and update. People often maintain open-source software as they have a real belief in its power and in how it frees us from the dominance of large and powerful companies.

    Not just for source code

    There are so many use cases of using Git that are not just versioning code. For my own teaching, I use Git to push my PowerPoint slides, source code and labs. Students can easily download the whole module at the start of the course and thus just to a "git pull" for any updates. Students, too, can mark typos in the material. You can find this at:

    https://github.com/billbuchanan/appliedcrypto

    Another interesting example is the District of Columbia and which publishes its laws through Git. This allows everyone involved to keep track of changes in the law and also spot errors and typos. If you are interested, the laws are marked up with XML and available at:

    https://github.com/DCCouncil/law-xml

    This, though, is the definitive source of the law, and not a copy from another system, and where a "pull request" allows someone to update a document, and then for the maintainer to review and change, if required.

    Conclusions

    To, me, Git is the one tool I could not do my work without. I love it, as I don't need a fancy GUI, I just drop down to the console and let my fingers to the walking. And, so, just like smashing Big Brother, Linus smashed a closed digital world and free us from the control of software. If we were to start the computer and software industry again, it would be Linus' route we would take and not the closed-source world of big business. If not for Git, we would probably be using Microsoft Backup 3.1 and dragging our files from one place to the next.

    9 min
  • Cryptography Fundamentals 10: ElGamal Encryption and Signatures

    Blog: https://billatnapier.medium.com/cryptography-fundamentals-elgamal-encryption-and-signature-2de5f16b1127

    ElGamal methods: https://asecuritysite.com/elgamal

    Introduction

    In research, we build on the shoulders of giants, and Taher Elgamal is one of the giants of cybersecurity. His work on Netscape led to the creation of SSL, and for which much of our Web security is still built on. Along with this, he published this paper in 1985 [here]:

    It was true classic, and has been reference over 12,500 times. Within the paper, Tahir outlined an encryption methods and a digital signature method. His 'base' was to take John Napier's logarithm, and make them discrete. This discrete element meant that we only dealt with positive integer values, and where we worked within a finite field. This field was defined by a prime number (p).

    While the core ElGamal encryption method was overtaken in its usage by RSA, and then by ECC (Elliptic Curve Cryptography), the signature method was adopted as the Digital Signature Standard (DSS) by NIST. This has since scaled into ECC to become ECDSA, and which is used by Bitcoin and Ethereum.

    Tahir studied electrical engineering in the late 1970s at Stanford University. It was there he met Marty Hellman and who helped him spark an interesting in cryptography. He received his PhD in 1984 and it was Marty introduced him to Paul Kocker at Netscape Communications. Together, Paul and Tahir worked on a method to implement end-to-end encryption, and published SSL 3.0 in November 1996:

    Examples are at:

    https://asecuritysite.com/elgamal

    The ElGamal Method

    Befre we start we need to look at some of the basics of logarithms and where:

    {g^a}^b is g^{ab}

    and:

    g^a . g^b = g^{a+b}

    To make these discrete to add (mod p) in our operations and where p is a prime number. This constrains our integrates with a finite field, between 0 and p-1.

    In the ElGamal method, Initially, Bob creates his public key by selecting a g value and a prime number (p) and then selecting a private key (x). He then computes Y which is:

    Y=g^x (mod p)

    His public key is (Y,g,p) and he will send this to Alice. Alice then creates a message (M) and selects a random value (k). She then computes a and b:

    a=g^k (mod p)

    b=y^k.M (mod p)

    Bob then receives these (a and b), and then uses his private key (x) to decrypt the values and discover the message:

    M=b/(a^x) (mod p)

    With the divide by (a^x) we basically take the inverse of (a^x) mod p, and then multiply. The operation works because:

    ElGamal and Signatures

    With ElGamal signing, Alice has a public key (y,g,p) and a private key of a. She then takes a message m and creates a signature (r,s). This signature can then be checked by Bob.

    With ElGamal, Alice selects a generator (g), prime number of p and a private key of a. Her public key is then (y,g,p) and where y is:

    y=g^a (modp)

    To sign a message (m) we generate a secret random number (k) and we must make sure:

    gcd(k,p−1)=1

    Next we compute:

    r=g^k (mod p)

    Next we compute:

    k^{−1} (mod p−1)

    and then:

    s=k^{−1}(h(m)−ar) (modp−1)

    The signature is then (r,s). Bob verifies the signature by computing two values:

    v1=y^r.r^s (mod p)

    and:

    v2=g^{h(m)} (mod p)

    If v1 is equal to v2

    the signature has been verified. The proof is given here:

    https://asecuritysite.com/elgamal/el_sig2

    While, ElGamal signing is not used these days, its method were applied into the Digital Signature Algorithm (DSA), and which was since been coverted into the Elliptic Curve Digital Signature Algorithm (ECDSA) method.

    Converting from discrete logs to elliptic curves

    In discrete logs we convert from:

    Y=g^a (mod p)

    to

    Y=a.G

    and where we have a exponential for discrete logs we have:

    Y = {g^a}^ b

    is equivalent to:

    Y=a.b.G

    and for a multiplication we have

    Y=g^a.g^b (mod p) = g^{a+b} (mod p)

    In elliptic curves we convert the multiplication to a point addition:

    Y = a.G + b.G = (a+b) G

    Converting from John Napier's Logarithms to Elliptic Curve Methods Around ten years ago, discrete log and RSA methods were riding right. But both of these methods have struggled with…medium.com

    This exponential becomes point multiplication, and multiply/division becomes point addition/subtraction.

    ElGamal and ECC

    But, Elliptic Curve Cryptography (ECC) methods are just everywhere just now. With ECC, we take points on a defined curve — such as Curve 25519 — and then perform point addition and subtraction. So how can we convert the ElGamal method into ECC? First, Alice first creates a private key (a) — and which is a random scalar value — and a public key (aP) — and which is a point on the elliptic curve. P is the base point on a curve. Alice's public key will then be:

    A=aP

    If Bob wants to send Alice an encrypted message (M), he creates a random value (k) and uses her public key (A) to produce a cipher message of:

    K=kP

    and then the next with:

    C=kA+M

    and where M is matched to a point on the elliptic curve. Now Alice receives (K) and (C), and computes:

    S=aK

    and then computes the message with:

    M=C−S

    As C and S will be points on the elliptic curve, this will be done with a point subtraction operation. Overall this will recover the original message as:

    C−S=kA+M−aK=kaP+M−akP=M

    The following is come Go code to implement this [taken from here]:

    package mainimport ( "fmt" "os" "go.dedis.ch/kyber" "go.dedis.ch/kyber/group/edwards25519" "go.dedis.ch/kyber/util/random")func ElEncrypt(group kyber.Group, pubkey kyber.Point, message []byte) ( K, C kyber.Point, remainder []byte) { // Embed the message (or as much of it as will fit) into a curve point. M := group.Point().Embed(message, random.New()) fmt.Printf("Message point:\t%s\n" , M.String()) max := group.Point().EmbedLen() if max > len(message) { max = len(message) } remainder = message[max:] // ElGamal-encrypt the point to produce ciphertext (K,C). k := group.Scalar().Pick(random.New()) // ephemeral private key K = group.Point().Mul(k, nil) // ephemeral DH public key S := group.Point().Mul(k, pubkey) // ephemeral DH shared secret C = S.Add(S, M) // message blinded with secret return}func ElDencrypt(group kyber.Group, prikey kyber.Scalar, K, C kyber.Point) ( message []byte, err error) { // ElGamal-decrypt the ciphertext (K,C) to reproduce the message. S := group.Point().Mul(prikey, K) // regenerate shared secret M := group.Point().Sub(C, S) // use to un-blind the message message, err = M.Data() // extract the embedded data return}func main() { M:="Testing" argCount := len(os.Args[1:]) if (argCount>0) {M= string(os.Args[1])} suite := edwards25519.NewBlakeSHA256Ed25519() // Alice's key pair (a,A) a := suite.Scalar().Pick(suite.RandomStream()) A := suite.Point().Mul(a, nil) fmt.Printf("Private key (Alice):\t%s\n" ,a.String()) fmt.Printf("Public key (Alice):\t%s\n" , A.String()) fmt.Printf("\n\n--- Now Bob will cipher the message for Alice\n") fmt.Printf("Bob's message:\t%s\n",M) m := []byte(M) K, C, _ := ElEncrypt(suite, A, m) fmt.Printf("\nBob cipher (K):\t%s\n" , K.String()) fmt.Printf("Bob cipher (C):\t%s\n" , C.String()) fmt.Printf("\n\n--- Now Alice will decipher the ciphertext (K,C) with her private key (a)\n") M_decrypted, err := ElDencrypt(suite, a, K, C) if err != nil { fmt.Println("Error: " + err.Error()) } fmt.Printf("\nOutput:\t%s",string(M_decrypted))}

    A sample run is:

    Private key (Alice): 7182fa86214b1672f36113d139b2f84ca6acbbf1dbe2202e2ad99665e4fdac00Public key (Alice): 31dfde321f1f56228feeacaeff9550c3d489ee5fd3e4e9d2e48fd41cfd9f09f6--- Now Bob will cipher the message for AliceBob's message: Testing 123Message point: 0b54657374696e6720313233aca5a2888970256a3bb93cde2898f95fcdfd96efBob cipher (K): c794b9c278298dc3abd64b0e3af62a2f7390c6c51c13a491930dea6b2dbc6ce4Bob cipher (C): 27ac77843effff5b723abe990e7175ba0c7659da0f5aec98421f0a89b78f2d82--- Now Alice will decipher the ciphertext (K,C) with her private key (a)Output: Testing 123

    And there you go, ElGamal using ECC:

    https://asecuritysite.com/elgamal/go_elgamal_ecc

    Partical Homomorphic Encryption with ElGamal

    With ElGamal public key encryption we have a public key of (Y,g,p) and a private key of (x). The cipher has two elements (a and b). With this, Bob selects a private key of x and the calculates Y= g^x (modp) for his public key. We can use it for partial homomorphic encryption, and where we can multiply the ciphered values. With this we encrypt two integers, and then multiply the ciphered values, and then decrypt the result.

    https://asecuritysite.com/homomorphic/go_el_homo

    https://asecuritysite.com/elgamal/elgamal_ps2

    g^a . g^b = g^{a+b}

    Other applications

    There are many other applications of the ElGamal method, including Authenticated Encryption and in Zero Knowledge Proofs. The days of using discrete logarithms are past, and most of the implementations use elliptic curve methods now. And, so, unlike many others, Tahir did not patent his method, and this allowed others to use it freely.

    10 min
  • Bill Buchanan - TETRA:BURST

    Blog: https://medium.com/asecuritysite-when-bob-met-alice/tetra-burst-42773a490b35

    Introduction

    Anyone can create a cipher. Basically, Bob and Alice do some modulo maths and could encrypt their secret messages into ciphertext by multiplying by 10 and adding 5, and then to decrypt back into plaintext, they would just subtract the ciphertext by 5 and divide by 10. The maths involved could then be defined by a Galois Field (GF)— and which is named after Évariste Galois. Bob and Alice could then keep their method secret from Eve (their adversary), and where they believe their method is secure and thus do not ask Trent to evaluate its security.

    But Eve is sneaky and tries lots of different ways to crack the cipher. Eventually, after trying to crack the ciphertext, she discovers the method, and can then crack all the future (and, possibly, previous) ciphers. Bob and Alice then carry on using the secret cipher method and would then have no way of knowing that Eve now knows their method.

    This approach is often known as "cooking your own crypto", and is not recommended in most implementations. Along with this, as Bob and Alice try to hide their method from Eve, the approach is "Security by obfuscation" rather than "Security-by-design".

    Cooking your own crypto

    There are many cases of propriety cryptography methods being used in production. In 2013, for example, researchers at the University of Birmingham found flaws in the key fobs related to the Volkswagen group vehicles. In fact, the encryption used in the Swiss-made Megamos transponder was so weak that an intruder only needed to listen to two transmitted messages from the fob in order to crack the key.

    The vulnerability related to the poor, proprietary cryptographic methods used by the device, and where the researchers found they could generate the transponder's 96-bit secret key and start the car in less than half an hour. The vulnerability has been well known since 2012, and code to exploit the flaw has circulated online since 2009. Yet, at the time, there was no product recall for the dozens of models that were affected, including Audi, Porsche, Bentley and Lamborghini, Nissan and Volvo. The research team were even stopped from publishing their work through the threat of legal action from Volkswagen.

    Testing, Evaluation and Standardization

    Along with the risk of discovering a secret method, the other major problem is that the method used to create a cipher is when it is not rigorously reviewed by experts. This can take years of reviewing and testing — both in the formal theory and in practice. Many companies, too, have bug bounties and which try to discover vulnerabilities in their code. To overcome this, NIST has created open competitions for the standardization of encryption methods. These have included standards related to symmetric key encryption (AES), hashing methods (SHA-3) and post-quantum cryptography (PQC). Once rigorously evaluated, the industry can then follow the standards defined, and where proprietary methods and implementations are often not trusted.

    With symmetric-key methods (where the same key is used to both encrypt and decrypt), at one time, we used a wide range of methods, such as DES, 3DES, RC2, RC4, Blowfish, and Twofish. To overcome this, NIST set up an operation standardization process for the Advanced Encryption Standard (AES). In the end, and after extensive testing and performance analysis, the Rijndael method was selected. It is now used in most systems, with either a 128-bit, a 192-bit or 256-bit encryption key. Overall, the larger the key size, the more difficult it is to brute force the key.

    The TETRA standard

    This week it has been reported that the TETRA (TErrestrial Trunked RAdio) standard [here] has a number of vulnerabilities in its cryptography. Overall, TETRA is used by many police and military forces across the world for encrypted radio. These vulnerabilities have existed for over a decade and could have led to the leakage of sensitive information.

    These vulnerabilities have been discovered by Midnight Blue and will be presented as "Redacted Telecom Talk" at Black Hat 2023 on 9 August 2023 [here]. As the work is so sensitive, there are many issues related to its disclosure, so the full details of the talk have not been released. But, it has involved over 18 months of responsible disclosure related to the cracking of TETRA-powered radios purchased from eBay.

    TETRA was first standardised by the European Telecommunications Standards Institute (ETSI) in 1996 and used by many radio manufacturers, such as Motorola and Airbus. It does not have open-source software and relies on cryptography which is secret and proprietary.

    TEA1 — Intentionally weak crypto

    Goverments around the world have generally used export controls on cryptography — in order to reduce security levels so that their own law enforcement agents have a good chance to crack encrypted traffic outside their own borders. One of the most famous was related to Netscape and who created the original version of TLS (Transport Layer Security) that created a secure channel for Web pages — the HTTPs that we see on most of our Web accesses now.

    This, though, had reduced security levels because of export control — with the RSA method used set at only 512 bits (and which is now easily crackable). As this key was used to pass the encryption key that was used in the secure tunnel, it meant that agencies could break the communications channel for HTTPs communications. We have since paid for this weakening —and with vulnerabilities such as Freak and BEAST. The vulnerability in TETRA, too, relates to similar issues and where the cryptography was reduced to comply with export controls. Within TERTA, the TEA1 method reduces the key size down to 80 bits, and, along with other vulnerabilities, allows the encrypted traffic to be cracked within minutes on a standard laptop.

    Along with this, researchers found other vulnerabilities with TETRA methods that released sensitive information — including within historical communications. The core vulnerability involved a jump-off from the main interface on the radio, and then which followed through with running malicious code execution on the process and then onto the signal processor and wifi hardware. This main chip on the device then contains a secure enclave, which stores the main encryption keys. The team were able to access this chip and discover the cryptography methods used and associated artefacts. For this, they have dubbed the vulnerability TETRA:BURST [here]:

    The reduced security method of TEA1 was discovered as having an encryption key of just 80 bits (normally, we would use a 128-bit key size, at least). A key size of 80 bits puts it within a range which can be cracked using GPU clusters. But, the research team found a "secret reduction step" which supported lower levels of randomization for the encryption key and which significantly reduced the key strength. Using this, the team were able to crack the communication with consumer-level hardware and with inexpensive radio equipment. Ultimately, the researchers define the attack as fairly trivial to implement.

    Vulnerabilities discovered

    A number of CVEs have already been defined for the vulnerabilities. These are [here]:

    • CVE-2022–24401. This involved the Air Interface Encryption (AIE) keystream generator allows for decryption oracle attacks.
    • CVE-2022–24402. This relates to the backdoor of the 80-bit key on the TEA1 algorithm — and which allows a trivial cipher crack.
    • CVE-2022–24404. This involves weaknesses in the AIE for malleability attacks.
    • CVE-2022–24403. This is a weak cryptographic scheme that allows attackers to deanonymize and track users.
    • CVE-2022–24400. This allows attackers to set the Derived Cypher Key (DCK) to 0.

    On the CVE database [here], these vulnerabilities are marked as "** RESERVED **" and will be populated soon.

    Conclusions

    What we have here is "Security by obscurity" and not "Security by design". It is difficult to keep anything a secret these days, and, as much as possible, methods should be open to assessment. Along with this, the reduction in the security level for TEA1 is causing major problems — just the Netscape restriction on TLS left us with a security legacy that took decades to address.

    11 min
  • Bill Buchanan - Passion, Leadership and Responsibility

    Blog: https://medium.com/asecuritysite-when-bob-met-alice/passion-leadership-and-responsibility-ded697c73c76

    Introduction

    I have been involved in enterprise and innovation for quite a while. I love it, and where I have had the opportunity to think and dream and kick-start things that flourish in the future. Some things have worked, and other things have not. And, we have been so lucky to have spun out three highly successful cybersecurity companies, and each of which has come from a seed of an idea but has been built by great people.

    And I am so pleased that people like Professor Mark Logan are now introducing words like enterprise and innovation back into academic approaches, as, for too long, it was all about research. Overall, research will go nowhere without adding some innovation and then some enterprise to take it to places where real people find real uses for it. In academia, there can be game-playing, and where the impact factor of a journal or the number of publications in the year can be seen as having an impact. But, the real impact happens in the real world and away from citation counts and impact factors. And, for grants, it is not the income that matters; it is what the grant actually does.

    Know the market and your customer

    Over the years, too, I have seen many approaches to enterprise and innovation, and at the core of this is knowing what the problem is that you are solving and that there is a market in what you are creating — in crude terms, it is, "Know the market and your customer".

    Having a passion for what you do

    At the core of a great company is the genuine passion for what you do as an organisation. It should never be false passion — but genuinely, from the heart — we love what we do. And I've observed that great companies focus on the quality of what they do and never dwell on what they have at the current time.

    Leadership and responsibility, and removing committees and bureaucracy

    A great company, too, prizes leadership and responsibility, and where job roles have lesser importance than someone's responsibility. I have never liked committees and bureaucracy; they are often created through a lack of trust in individuals. Few committees ever make strategic decisions, and few committees ever innovate anything.

    And, so, to me, the best companies/organisations have leaders who are generally self-starters — they don't need to be prompted to do something — they just know it is right to progress something. These leaders, hopefully, should be instantly identifiable in your organisation, and who you could communicate with in an instance. Great leaders should not hide behind administrative support but actively engage with those who have questions about their approaches.

    Stop wasting time, and don't blame

    To me, companies should always try to break down these barriers to advancement and try to minimise the time in meetings. For me, I despair at the two-hour meetings with fixed agenda — and with a growing list of attendees. I've always found that time spent discussing will grow exponentially with the number of people in a meeting. The best meetings for me, as those which communicate things and have an open place to discuss any concerns, and then they finish on time.

    And great companies often do not pinpoint blame on individuals. They will investigate what went wrong but will never end up pin-pointing any individual. This approach allows individuals to feel confident that they can take responsibility without feeling that, if something fails, they will end up being blamed for the failure.

    My Bluffers guide to creating a great company/organisation

    So, here's my bluffers guide to creating a great company/organisation:

    • Be passionate about what you do. Love your business.
    • Understand the market and your customer's needs.
    • Promote leadership wherever possible.
    • Do not blame individuals for mistakes.
    • Recruit amazing staff, look after them, reward them well, and keep them.
    • Break down the hierarchy.
    • Focus on responsibilities rather than job roles.
    • Promote enterprise and innovation wherever possible.
    • Remove bureaucracy wherever you find it.
    • Remove committees wherever possible.
    • Be agile, move fast and execute quickly.
    • Small teams often work best.
    • Support the generation of ideas from every part of the business.
    • Praise success wherever possible, and allow others to share in the success.
    • Know when something fundamentally isn't working, and stop it.

    And, the signs:

    • There is a genuine passion in the company/organisation.
    • There is a core focus on quality.
    • Leadership drives the company.
    • Leaders are highly visible to all and are self-starters.
    • There is a common and shared vision.
    • There is accountability in decisions.
    • There is open communication for debate within teams/company.
    • Success is communicated within teams and where teams genuinely feel proud of their achievements.
    Conclusions

    Avoid hooking up with a company or organisation with followers which is full of committees and line managers. Oh, and get the best HR people possible! For a start-up, the HR function is likely a core part of the success or failure of a company.

    For me, I love innovating, and I love teaching and researching cryptography, and my university has given me the space to do these things. I have a passion for education, and I love what I do. Go find your passion if you have not already found it …

    8 min
  • Bill Buchanan - A Bluffers Guide To JWTs

    Related blog: https://medium.com/asecuritysite-when-bob-met-alice/tokens-jwt-and-google-tink-c6b915d387e8

    And: https://billatnapier.medium.com/hmac-or-public-key-signing-of-jwts-64084aff10ef

    Introduction

    My Top 20 important things about JWTs:

    1. JWT is a JSON Web Token and is pronounced "jot". JSON objects support human-readable text and are used in many applications, such as with NoSQL databases.
    2. You should not trust a JWT unless it is cryptographically signed.
    3. For authorization, a captured JWT can be replayed and "played back" to provide a malicious entry or rights into a system.
    4. JWTs should never be trusted before their issue date and their not-before date and never trusted after their expiry.
    5. JWTs have been defined as an RFC standard with RFC7519.
    6. The format is URL friendly and is Base64URL encoded.
    7. A JWT token has three main parameters separated by a period ("."), and which are the header, the payload and the signature.
    8. The header is typically not encrypted and defines the signature algorithm ("alg") and the type ("typ").
    9. The payload is typically not encrypted and uses a Base64 format. The payload can typically be seen by anyone who captures it.
    10. "ey" is a typical field starting part of a parameter in the header and body of a token as '{"' encoded in Base64 is "ey==". You can tell if a token is not encrypted with an "ey" as the start of the header and body parameters.
    11. The registered claims of a token are iss (Issuer), sub (Subject), aud (Audience), iat (Issued At), exp (Expires), nbf (Not Before), and jti (JWT ID).
    12. The claim fields are not mandatory and just a starting point for defining claims.
    13. A claim is asserted about a subject, and where we have a claim name and a claim value in a JSON format.
    14. With an HMAC signature, the issuer and validator must share the same secret symmetric key.
    15. If you use HMAC to sign the tokens, a breached secret key will compromise the signing infrastructure.
    16. The two main public key signing methods are RSA and ECDSA.
    17. The time of a token is represented as the number of seconds from 1 January 1970 (UTC).
    18. Each day of a JWT token is represented by 86,400 seconds.
    19. An unsecured JWT does not have encryption or a signature. This is bad! it is represented in the header parameter with an "alg" of "none" and an empty string for the JWS Signature value.
    20. A JWT can be encrypted (but this is optional). For public key methods, we can use either RSA and AES, or we can use a wrapped key.

    And a debate I've had with many development teams:

    What's a token?

    So, what's a token? Well, it is basically a way to encapsulate data in a well-defined format that has a signature from the issuer. For this, we either sign using HMAC (HMAC-256, HMAC-384 or HMAC-512), RSA signing or ECC signing. The HMAC method requires the use of a secret symmetric key, whilst RSA and ECC use public key encryption. The problem with HMAC is that if someone discovers the secret key, they could sign valid tokens. For enhanced security, we typically use public key encryption, where we sign with a private key and then validate with the public key.

    In this case, we will use Google Tink to create JWTs (JSON Web Tokens) and which are signed with elliptic curve cryptography. For this, we will use either NIST P-256 (ES256), NIST P-384 (ES384) or NIST P512 (ES512) for the curves. Overall, we do not generally encrypt the payload in JWT, so it can typically be viewed if the token is captured.

    JWT format

    A JWT token splits into three files: header, payload and signature (Figure 1).

    Figure 1: JWT format The header parameter

    The header contains the formation required to interpret the rest of the token. Typical fields are "alg" and "kid", and these represent the algorithm you use (such as "ES256") and the ID, representively. The default type ("type") will be "JWT". Other possible fields include "jwk" (JSON Web key), "cty" (Content type), and "x5u" (X.509 URL). An example header for a token that uses ES384 signatures and with an ID of "s5qe-Q" is:

    {"alg":"ES384", "kid":"s5qe-Q"} The payload parameter

    The payload is defined in JSON format with a key-pair setting. For a token, we have standard claim fields of iss (Issuer), sub (Subject), aud (Audience), iat (Issued At), exp (Expires At), nbf (Not Before), and jti (JWT ID). The claim fields are not mandatory and are just a starting point — and where a developer can add any field that they want. An example field is:

    {"aud":"qwerty", "exp":1690754794, "iss":"ASecuritySite", "jti":"123456", "sub":"hello"}

    The time is defined in the number of seconds past 1 January 1970 UTC. In this case, 1690754794 represents Sunday 30 Jun 22:06:34:

    The token signing parameter

    There are two ways to sign a token: with an HMAC signature or with a public key signature. With HMAC, we create a shared symmetric key between the issuer and the validator. For public key encryption, we use either RSA or ECDSA. For these, we create a signature by signing the data in the token with the private key of the creator of the token, and then the client can prove this with the associated public key. For public key signing, the main signing methods are:

    • ES256. ECDSA using NIST P256 with SHA-256.
    • ES384. ECDSA using NIST P384 with SHA-384.
    • ES512. ECDSA using NIST P512 with SHA-512.
    • RS256. RSASSA-PKCS1-v1_5 with the SHA-256 hash.

    and for HMAC:

    • HS256. HMAC with SHA-256.
    • HS384. HMAC with SHA-384.
    • HS512. HMAC with SHA-512.

    In public key signing, we have a key pair to sign the token:

    And with HMAC, we share a secret signing key:

    Encrypting the payload

    A JWT can be encrypted, but this is optional. For public key methods, we can use either RSA and AES or a wrapped AES key. An "alg" method of "RSA1_5" will use 2,048-bit RSA encryption with RSAES-PKCS1-v1_5, "A128KW" will use 128-bit Key Wapping and "A256KW" uses 256-bit Key Wapping. With key wrapping, the private key is encrypted with a secret key. Both the issuer and verifier will know this secrete key.

    For symmetric key methods, we can use "A128CBC-HS256" (AES-CBC) and "A256CBC-HS512" (HMAC SHA-2). It is possible to also use ECDH-ES (Elliptic Curve Static) for key exchange methods

    An example token

    An example token is:

    eyJhbGciOiJFUzI1NiIsICJraWQiOiJ3WHd6dVEifQ.eyJhdWQiOiJxd2VydHkiLCAiZXhwIjoxNjkwNzU0Nzk0LCAiaXNzIjoiQVNlY3VyaXR5U2l0ZSIsICJqdGkiOiIxMjM0NTYiLCAic3ViIjoiaGVsbG8ifQ.cAXunJHLRrqFfJStJTFlwkUTze6K8EpwOui9abDeiSBcR5WeOEpXCSUQBnS_VdVnLsmVV2AWUX0kOTqIWERcMQ

    We then have:

    • Header: eyJhbGciOiJFUzI1NiIsICJraWQiOiJ3WHd6dVEifQ
    • Payload: eyJhdWQiOiJxd2VydHkiLCAiZXhwIjoxNjkwNzU0Nzk0LCAiaXNzIjoiQVNlY3VyaXR5U2l0ZSIsICJqdGkiOiIxMjM0NTYiLCAic3ViIjoiaGVsbG8ifQ
    • Signature: cAXunJHLRrqFfJStJTFlwkUTze6K8EpwOui9abDeiSBcR5WeOEpXCSUQBnS_VdVnLsmVV2AWUX0kOTqIWERcMQ

    These are in Base64 format, and we can easily decode the header as:

    {"alg":"ES256", "kid":"wXwzuQ"}

    and the payload as:

    {"aud":"qwerty", "exp":1690754794, "iss":"ASecuritySite", "jti":"123456", "sub":"hello"}

    The signature value will be in a byte array format.

    Sample code

    With Google Tink, we can create a token with the fields using:

    expiresAt := time.Now().Add(time.Hour) subject:= "CSN09112" audience := "Sales" issurer := "ASecuritySite" jwtid := "123456" rawJWT, _ := jwt.NewRawJWT(&jwt.RawJWTOptions{ Subject: &subject, Audience: &audience, Issuer: &issurer, ExpiresAt: &expiresAt, JWTID: &jwtid, })

    Next we will generate an ECC private key using either NIST P256, NIST P-384 or NIST P-512. In the following, we create a private key (priv) and which will be used to sign the token:

    priv,_ =keyset.NewHandle(jwt.ES256Template()signer, _ := jwt.NewSigner(priv)token, _ := signer.SignAndEncode(rawJWT)

    We can then create the public key from the private key, and validate the token with this key:

    pub, _:= priv.Public()verifier, _ := jwt.NewVerifier(pub)

    The full code is [here]:

    package mainimport ( "fmt" "time" "os" "strconv" "github.com/google/tink/go/jwt" "github.com/google/tink/go/keyset" "github.com/google/tink/go/insecurecleartextkeyset")func main () { priv, _ := keyset.NewHandle(jwt.ES256Template()) expiresAt := time.Now().Add(time.Hour) subject:= "CSN09112" audience := "Sales" issurer := "ASecuritySite" jwtid := "123456" t:=0 argCount := len(os.Args[1:]) if (argCount>0) {subject= string(os.Args[1])} if (argCount>1) {audience= string(os.Args[2])} if (argCount>2) {issurer= string(os.Args[3])} if (argCount>3) {jwtid= string(os.Args[4])} if (argCount>4) {t,_ = strconv.Atoi(os.Args[5])} switch t { case 1: priv,_ =keyset.NewHandle(jwt.ES256Template()) case 2: priv,_ =keyset.NewHandle(jwt.ES384Template()) case 3: priv,_ =keyset.NewHandle(jwt.ES512Template()) } pub, _:= priv.Public() rawJWT, _ := jwt.NewRawJWT(&jwt.RawJWTOptions{ Subject: &subject, Audience: &audience, Issuer: &issurer, ExpiresAt: &expiresAt, JWTID: &jwtid, }) signer, _ := jwt.NewSigner(priv) token, _ := signer.SignAndEncode(rawJWT) verifier, _ := jwt.NewVerifier(pub) validator, _ := jwt.NewValidator(&jwt.ValidatorOpts{ExpectedAudience: &audience,ExpectedIssuer: &issurer}) verifiedJWT, _:= verifier.VerifyAndDecode(token, validator) id,_:=verifiedJWT.JWTID() sub,_:=verifiedJWT.Subject() aud,_:=verifiedJWT.Audiences() iss,_:=verifiedJWT.Issuer() at,_:=verifiedJWT.IssuedAt() ex,_:=verifiedJWT.ExpiresAt() fmt.Printf("Public key:\t%s\n",priv) fmt.Printf("Public key:\t%s\n\n",pub) fmt.Printf("Token:\t%s\n\n",token) fmt.Printf("Subject:\t%s\n",sub) fmt.Printf("Audience:\t%s\n",aud) fmt.Printf("Issuer:\t\t%s\n",iss) fmt.Printf("JWT ID:\t\t%s\n",id) fmt.Printf("Issued at:\t%s\n",at) fmt.Printf("Expire at:\t%s\n",ex) fmt.Printf("\n\nAdditional key data\n") exportedPriv := &keyset.MemReaderWriter{} insecurecleartextkeyset.Write(priv, exportedPriv) fmt.Printf("Private key: %s\n\n", exportedPriv) exportedPub := &keyset.MemReaderWriter{} insecurecleartextkeyset.Write(pub, exportedPub) fmt.Printf("Public key: %s\n\n", exportedPub)}

    A sample run proves the process [here]:

    Public key: primary_key_id:1926408156 key_info:{type_url:"type.googleapis.com/google.crypto.tink.JwtEcdsaPrivateKey" status:ENABLED key_id:1926408156 output_prefix_type:TINK}Public key: primary_key_id:1926408156 key_info:{type_url:"type.googleapis.com/google.crypto.tink.JwtEcdsaPublicKey" status:ENABLED key_id:1926408156 output_prefix_type:TINK}Token: eyJhbGciOiJFUzI1NiIsICJraWQiOiJjdEtuM0EifQ.eyJhdWQiOiJxd2VydHkiLCAiZXhwIjoxNjkwNzUxNTI0LCAiaXNzIjoiQVNlY3VyaXR5U2l0ZSIsICJqdGkiOiIxMjM0NTYiLCAic3ViIjoiaGVsbG8ifQ.qfui2u9hBpEgiQQeeWNJtSanyl4rbYkViIZJxVmBvCsP72ovcT20qC35YbQOh7Q8cCqA37Fk8OXWSQ-geg6E-QSubject: helloAudience: [qwerty]Issuer: ASecuritySiteJWT ID: 123456Issued at: 0001-01-01 00:00:00 +0000 UTCExpire at: 2023-07-30 21:12:04 +0000 GMTAdditional key dataPrivate key: .{primary_key_id:1926408156 key:{key_data:{type_url:"type.googleapis.com/google.crypto.tink.JwtEcdsaPrivateKey" value:"\x12F\x10\x01\x1a \xcdPtI\x03)\xb0\xf7H9'\x1e\x94t\xaaa\x99\xf8ڍv\xcf\xd6|\x1a\x1aV6H!\xda\x00\" \xc2�¥\xfaD\x16\xb2\xfa\xd7\x00\xfe\xba\xe4\xf3\xed%\x03\x9a^\x1d\x9f\x93_\xf3\x1f\xd9W\x90\x8aâX\x1a p\xf7,_}\x13\xff\x84\x9c\xc6j\xdaͯ\xc7\x1b.\xb2|\x19ØŽ\xfb\xa9j\x05\xb3NF\xc4\x7f\xcc" key_material_type:ASYMMETRIC_PRIVATE} status:ENABLED key_id:1926408156 output_prefix_type:TINK} .nil.}Public key: .{primary_key_id:1926408156 key:{key_data:{type_url:"type.googleapis.com/google.crypto.tink.JwtEcdsaPublicKey" value:"\x10\x01\x1a \xcdPtI\x03)\xb0\xf7H9'\x1e\x94t\xaaa\x99\xf8ڍv\xcf\xd6|\x1a\x1aV6H!\xda\x00\" \xc2�¥\xfaD\x16\xb2\xfa\xd7\x00\xfe\xba\xe4\xf3\xed%\x03\x9a^\x1d\x9f\x93_\xf3\x1f\xd9W\x90\x8aâX" key_material_type:ASYMMETRIC_PUBLIC} status:ENABLED key_id:1926408156 output_prefix_type:TINK} .nil.} Conclusions

    There are many risks in using JWTs, especially in capturing a token and playing it back. The expiry date should thus be set so that it would limit the impact of any malicious use.

    Using public key encryption to sign JWTs is a good method, as the authenticity of the token can be proven with the associated public key. With an HMAC method, we need to share a secret key, which could cause a data breach.

    And, finally, which signature method should you pick? Find out here:

    17 min
  • Bill Buchanan - Noyce, Moore and Grove — A Template for Spin-out/Start-up Success?

    Blog post: https://medium.com/asecuritysite-when-bob-met-alice/noyce-moore-and-grove-a-template-for-spin-out-start-up-success-b67d9795154a

    Introduction

    So, is there a formula for a successful start-up/spin-out — and if you followed it, you would be guaranteed success? For this, many people approach me and say, "I want to have a spin-out. What should I do?". To me, this is a little like saying, "I want to fly, can you give me wings?". So, let me lay out a few things that I have learned over the past two decades of being involved in spin-out companies.

    Overall, we have been very lucky in our spin-outs, with three highly successful ones, and where two have been bought out (Zonefox and Symphonic), and the third is expanding fast within digital forensics (Cyacomb). But, as they say, "The Harder I Practice, the Luckier I Get". We have had failures, but every time our team has licked their wounds and come back stronger. And the one thing, though, I've observed is that the leadership of an innovative company often needs to change as it evolves, and those leading it need to know when they need to move aside and let others take their place.

    So, I'm going to define the three stages as: Visionary, Strategy and Grit, and where there are very different leaders at each stage. But, fundamentally, the first two stages set up the culture and approach of the company, and which are fundamental to its long-term beliefs and ideals. Overall, few companies in the third stage can turn their ship and travel in a different direction. The approach of IBM, for example, is still one of an engineering approach to their work and one built on rewarding innovation.

    Forgive me, I'm technical

    And, so I am a cryptography professor, and not a business one, so please forgive me for not covering the core literature in the areas of business. I am also highly technical, and that is what I love. I would never want to be a cut-throat business person and would never want to be. I love inventing things and seeing ideas grow from seeds. And one thing I know is when my role is complete as part of the innovation process and when to move aside.

    But, deeply technical people are at the core of creating a successful spin-out, along with people with a vision. And, so, I would like to lay out a basic template of my observations in creating a successful spin-out — and based on the ones we have produced. To me, also, a great technical company should have a core of theoretical work, and where the best work can come from academic collaborations. In academia, there is an attention to detail and theory, and which makes sense of the complex world of invention and discovery. But, the magic comes from practical implements, and where the best collaborations mix practice with theory.

    So, my basic template for success is to get the right leadership team in place, and get the right leader for the right time. A core part of this is knowing when the leader should move aside and let someone else take over. For this, I'll map it to the success of Intel and its first three employees: Robert Noyce, Gordon Moore and Andy Grove.

    Stage 1: Robert Noyce — the Visionary (1968–1975)

    If there's a superstar of our digital era, it must be Robert Noyce. Imagine inventing the one thing that now drives virtually everything in our digital age: the integrated circuit. It all started in the late 1950s with John Bardeen and Walter Brattain at Bell Labs and who first invented the transistor. William Shockley advanced the concept with the creation of the bipolar transistor. Bardeen and Brattain were a great research team and has a great balance of theoretical skills with practical ones. Brattain did the theory, and Bardeen did the practical work. All three eventually received a Nobel Prize for their work — with Brattain being one of the few people to ever get two Nobel Prizes.

    While Bell Labs was a hub of innovation at the time, Shockley wanted to take a good deal of the credit for the invention of the transistor and left Bell Labs to set up his own company in 1955: Shockley Semiconductor. For this, we recruited Robert Noyce and Gordon Moore to work on his ideas. But Shockley was a difficult boss and had an overbearing approach to his management style. This caused eight of Shockley's employees — including Robert Noyce and Gordon Moore — to leave the company and start their own venture with the support of Fairchild Camera and Instrument. It was there, in 1961, that Robert created one of the most significant patents of all time:

    It outlined a magical way of doping a semiconductor substrate and producing an integrated circuit:

    This invention differed from Jack Kilby's work at Texas Instruments, as Robert outlined a monolithic circuit while Jack defined a hybrid circuit approach. And, so, Fairchild grew fast as a leader in semiconductors, but as the company grew, Robert increasingly missed the days of true innovation and decided to team up with Gordon Moore to create Integrated Electronics (which would end up just being known as Intel).

    And, so, Robert was the anchor for the creation of Intel. A true visionary and someone that people trusted and listened to. It was thus not difficult for Andy Rock to find the seed funding for the start-up — as it had Robert's name on it. Those who invested in the company were not investing in the company and its projected product line but in Robert.

    In Stage 1 we thus have the visionary leader. The person who can see beyond the near future and build a company that could scale towards their vision, and someone who both inspired people to believe and someone who others could trust with the vision.

    And, so, Robert led Intel from 1968 to 1975 but knew the time that he needed to hand over to someone else. And, that needed to be someone who had a core understanding of the technology required to scale Intel: Gordon Moore.

    Stage 2: Gordon Moore — the technical and strategic genius (1975–1987)

    In Stage 2, we move from the visionary leader to the strategic leader, and there was no better person than Gordon Moore (and who created the mighty Moore's Law — and which is still relevant to this day). Gordon had an eye for detail and quality. For Intel to succeed, they needed someone to convert the vision shown by Noyce to something that matched the market. For this, he invested heavily in R&D and made Intel a world leader in the memory market. But, he showed his strategic brilliance by spotting the opportunity to initiate work in microprocessors.

    As we all know, in 1969, Intel was designing some chips for Busicom and decided to integrate these into a single device, which could be programmed with software. The designer was Ted Hoff, and he produced the first microprocessor: the 4004. And, so, as the memory market became crowded and profits fell, Gordon moved Intel out of it and ramped up the development of the 8-bit and 16-bit microprocessors. The device that sprang out of this development was the Intel 8086, which — luck would have it — was the processor selected for the IBM PC. It was luck and strategy, and Gordon was a core part of this. Most CEOs would have pushed forward in the memory market, but Gordon focused Intel's R&D on new markets.

    Gordon Moore was thus the second phase leader and the one who could stop opportunities and be in the right place at the right time to exploit them. Without his technical genius, the company would have struggled to understand how to scale R&D into emerging markets.

    Stage 3: Andy Grove — the detail (1987–1998)

    And now we need the last piece of the puzzle … Andy Grove. Intel had grown up as a company of idealists and lacked a "Us and Them" approach to management. Noyce, Moore and Grove had led the company, but they were colleagues. Many remember that it was often difficult to find Gordon in the company when they visited him, as he sat in a cubical in the open plan set up and shared the same physical space with others in the company. There were no fancy trimmings for Gordon in his CEO role — he was as much a worker as any other.

    And both Robert and Gordon had a gentle approach to their management style, but Andy brought an edge that the congenial Moore and Noyce could never give.

    At eight years old, Andy escaped with his mother from the Nazis and left Hungary at the age of 20 during the Hungarian Revolution. He arrived in the US as a refugee with no money but with a passion for learning. Eventually, he gained his PhD from the University of California, Berkeley.

    And, so, Andy provided the grit and desire to succeed that Intel needed, and, as with Gordon, he had an eye for quality and in making sure that everything that Intel did was at the highest possible technical level.

    And so it was Andy who had the grit to move Intel out of its core memory business and into microprocessors. He had a knack for taking complex problems and distilling them down into strategies that were easy for those involved to understand. Perhaps it was because he was an engineer first and then had to learn about management and strategic approaches.

    His strategy was to move Intel out of memory and straight into the PC. The natural choice at the time for the processor in the PC was Motorola, but Grove managed to get the technical support in place for the Intel chip, and that allowed engineers to develop their prototypes. And, what did Grove do about the expertise in memory? He put it to good use in integrating SRAM caches into the processor, which massively speeded up their operation.

    Andy thus had the grit that Intel required to take it into new markets and win:

    The most important role of managers is to create an environment where people are passionately dedicated to winning in the marketplace. Fear plays a major role in creating and maintaining such passion. Fear of competition, fear of bankruptcy, fear of being wrong and fear of losing can all be powerful motivators.

    Conclusions

    Moore and Noyce drove Intel to become one of the world's most powerful companies. The team had a perfect balance … Noyce inspired everyone he met and built an initial customer base, while Moore built technical excellence and then followed through. It was left to Grove to focus on detail and excellence. William Shockley failed in the market as he couldn't share success with others, while Moore, Noyce and Grove built a culture of collaboration and in taking shared ownership of the company they built.

    The first stages of a company are thus so important is building its culture into the future. If those involved in those first stages do not act in the right way, then the company may be doomed to have the wrong approaches to its employees and customers. The initial leaders are the ones that people should look up to and be inspired by. This is not often through business practice, but having core scientific and technical expertise in their field.

    So, get your team in place … a visionary, a technical genius, and a true leader with grit. But, knowing the best leader at any given time and knowing when to hand over to someone else can take the next great step forward. And, go do something wonderful …

    16 min

About ASecuritySite Podcast

From the publisher's feed

A security podcast is hosted by Professor William (Bill) Buchanan OBE, a world-renowned Information security professional and educator. Join Bill as he interviews and discusses the state-of-the-art…

More shows like ASecuritySite Podcast

Risky Business by Risky Business Media

Risky Business

374 Listeners

The Quanta Podcast by Quanta Magazine

The Quanta Podcast

542 Listeners

Darknet Diaries by Jack Rhysider

Darknet Diaries

8,061 Listeners

Risky Bulletin by Risky Business Media

Risky Bulletin

46 Listeners

The Rest Is Classified by Goalhanger

The Rest Is Classified

1,129 Listeners