Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add JitsiXmppStringprep #105

Merged
merged 13 commits into from
Apr 26, 2024
9 changes: 8 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
<packaging>bundle</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<smack.version>4.4.6</smack.version>
<!-- Make sure this matches the version of the jxmpp artifacts inherited from smack. -->
<jxmpp.version>1.0.3</jxmpp.version>
<smack.version>4.4.8</smack.version>
<junit.version>5.10.0</junit.version>
<kotlin.version>1.9.10</kotlin.version>
<kotest.version>5.7.2</kotest.version>
Expand Down Expand Up @@ -39,6 +41,11 @@
<artifactId>smack-xmlparser-stax</artifactId>
<version>${smack.version}</version>
</dependency>
<dependency>
<groupId>org.jxmpp</groupId>
<artifactId>jxmpp-stringprep-rocksxmppprecis</artifactId>
<version>${jxmpp.version}</version>
</dependency>
<dependency>
<groupId>org.jitsi</groupId>
<artifactId>jitsi-utils</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,12 @@ public C parse(XmlPullParser parser, int depth, XmlEnvironment xmlEnvironment)
namespace = parser.getNamespace();

if (logger.isLoggable(Level.FINEST))
{
logger.finest("Will parse event " + eventType
+ " for " + elementName
+ " ns=" + namespace
+ " class=" + packetExtension.getClass().getSimpleName());
+ " for " + elementName
+ " ns=" + namespace
+ " class=" + packetExtension.getClass().getSimpleName());
}

if (eventType == XmlPullParser.Event.START_ELEMENT)
{
Expand All @@ -122,7 +124,7 @@ public C parse(XmlPullParser parser, int depth, XmlEnvironment xmlEnvironment)
if (provider == null)
{
//we don't know how to handle this kind of extensions.
logger.fine("Could not add a provider for element "
logger.fine("Could not find a provider for element "
+ elementName + " from namespace " + namespace);
}
else
Expand Down
51 changes: 51 additions & 0 deletions src/main/kotlin/org/jitsi/xmpp/Smack.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* Copyright @ 2024 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.xmpp

import org.jitsi.utils.logging2.createLogger
import org.jitsi.xmpp.stringprep.JitsiXmppStringprep
import org.jivesoftware.smack.SmackConfiguration
import org.jivesoftware.smack.parsing.ExceptionLoggingCallback
import org.jivesoftware.smackx.bytestreams.socks5.Socks5Proxy
import org.jxmpp.JxmppContext
import org.jxmpp.jid.impl.JidCreate

object Smack {
val logger = createLogger()

fun initialize(useJitsiXmppStringprep: Boolean = true) {
logger.info("Setting XML parsing limits.")
System.setProperty("jdk.xml.entityExpansionLimit", "0")
System.setProperty("jdk.xml.maxOccurLimit", "0")
System.setProperty("jdk.xml.elementAttributeLimit", "524288")
System.setProperty("jdk.xml.totalEntitySizeLimit", "0")
System.setProperty("jdk.xml.maxXMLNameLimit", "524288")
System.setProperty("jdk.xml.entityReplacementLimit", "0")

if (useJitsiXmppStringprep) {
// Force XmppStringPrepUtil to load before we override the context, otherwise it gets reverted.
// https://github.com/igniterealtime/jxmpp/pull/44
JidCreate.from("example")
logger.info("Using JitsiXmppStringprep.")
JxmppContext.setDefaultXmppStringprep(JitsiXmppStringprep.INSTANCE)
}

// if there is a parsing error, do not break the connection to the server(the default behaviour) as we need
// it for the other conferences.
SmackConfiguration.setDefaultParsingExceptionCallback(ExceptionLoggingCallback())
Socks5Proxy.setLocalSocks5ProxyEnabled(false)
}
}
115 changes: 115 additions & 0 deletions src/main/kotlin/org/jitsi/xmpp/stringprep/JitsiXmppStringprep.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* Copyright @ 2024 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.xmpp.stringprep

import org.jxmpp.stringprep.XmppStringprep
import org.jxmpp.stringprep.XmppStringprepException
import org.jxmpp.stringprep.rocksxmppprecis.RocksXmppPrecisStringprep
import rocks.xmpp.precis.PrecisProfile
import java.net.IDN
import java.text.Normalizer
import java.util.regex.Pattern

/**
* Extends [RocksXmppPrecisStringprep] to allow underscores (_) in the domain part.
*
* This is needed because jitsi-meet URLs of the form https://domain/tenant/room get translated into a JID of the
* form [email protected], and the tenant field has been allowed to use _ and % for a long time (in
* fact '.' in the tenant is translated into '_', while unicode characters get url encoded into e.g. %c3%9f).
*/
class JitsiXmppStringprep : XmppStringprep by RocksXmppPrecisStringprep.INSTANCE {
override fun domainprep(string: String?): String {
try {
return idnWithUnderscoreProfile.enforce(string)
} catch (e: IllegalArgumentException) {
throw XmppStringprepException(string, e)
}
}

companion object {
val INSTANCE = JitsiXmppStringprep()
private val idnWithUnderscoreProfile = IDNWithUnderscoreProfile()
}
}

/**
* Based on [PrecisProfiles.IDN], but allows underscores.
*/
class IDNWithUnderscoreProfile : PrecisProfile(false) {
override fun prepare(input: CharSequence): String {
// We're calling toASCII and toUnicode without the [IDN.USE_STD3_ASCII_RULES] flag, so we have to do the
// (relaxed) verification.
val ascii = verifyLDHU(IDN.toASCII(input.toString()))
return verifyLDHU(IDN.toUnicode(ascii))
}

/**
* Assert that, after splitting [s] into labels separated, each label:
* -- Is not empty.
* -- All ASCII characters are Letters/Digits/Hyphen/Underscore/Percent.
* -- Does not begin or end with a hyphen.
*
* Based on the implementation in java's IDN, but relaxed to accept _ and % as part of a label.
*
* @throws IllegalStateException if any of the assertions fail.
*/
private fun verifyLDHU(s: String) = s.also {
val dest = StringBuffer(s)
require(dest.isNotEmpty()) { "Empty label is not a legal name" }

for (i in s.indices) {
require(!dest[i].code.isNonLDHUPAsciiCodePoint()) { "Contains non-LDHU ASCII characters: ${dest[i]}" }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error message should presumably have P added to it

if (dest[i].isLabelSeparator()) {
require(i != 0) { "Empty label is not a legal name" }
require(dest[i - 1] != '-') { "Label has trailing hyphen" }
require(!dest[i - 1].isLabelSeparator()) { "Empty label is not a legal name" }
require(i == dest.length - 1 || dest[i + 1] != '-') { "Label has leading hyphen" }
require(i == dest.length - 1 || !dest[i + 1].isLabelSeparator()) { "Empty label" }
}
}
require(dest[0] != '-' && dest[dest.length - 1] != '-') { "Has leading or trailing hyphen" }
}

override fun applyWidthMappingRule(charSequence: CharSequence) = widthMap(charSequence)
override fun applyAdditionalMappingRule(charSequence: CharSequence) =
LABEL_SEPARATOR.matcher(charSequence).replaceAll(".")
override fun applyCaseMappingRule(charSequence: CharSequence) = charSequence.toString().lowercase()

override fun applyNormalizationRule(charSequence: CharSequence) =
Normalizer.normalize(charSequence, Normalizer.Form.NFC)

override fun applyDirectionalityRule(charSequence: CharSequence) = charSequence

companion object {
private val dots = listOf('.', '\u3002', '\uFF0E', '\uFF61').toCharArray()
private val LABEL_SEPARATOR = Pattern.compile("[${dots.joinToString(separator = "")}]")

private fun Char.isLabelSeparator() = dots.contains(this)

/**
* Return true if [this] is a code for an ASCII character that is not a Letter/Digit/Hyphen/Underscore/Percent.
*/
private fun Int.isNonLDHUPAsciiCodePoint(): Boolean {
return (this in 0x0000..0x0024) ||
(this in 0x0026..0x002C) ||
(this == 0x002F) ||
(this in 0x003A..0x0040) ||
(this in 0x005B..0x005e) ||
(this == 0x0060) ||
(this in 0x007B..0x007F)
}
}
}
Loading
Loading